As far as the .NET platformis concerned, the most fundamental programming construct is the class
type. Formally, a class is a user-defined type that is composed of field data (often called member
variables) and members that operate on this data (such as constructors, properties, methods,
events, and so forth). Collectively, the set of field data represents the “state” of a class instance (otherwise
known as an object). The power of object-based languages such as C# is that by grouping
data and related functionality in a class definition, you are able to model your software after entities
in the real world.
To get the ball rolling, create a new C# Console Application named SimpleClassExample. Next,
insert a new class file (named Car.cs) into your project using the Project äAdd Class menu selection,
A class is defined in C# using the class keyword. Here is the simplest possible declaration:
class Car
{
}
Once you have defined a class type, you will need to consider the set of member variables that
will be used to represent its state. For example, you may decide that cars maintain an int data type
to represent the current speed and a string data type to represent the car’s friendly pet name. Given
these initial design notes, update your Car class as follows:
class Car
{
// The 'state' of the Car.
public string petName;
public int currSpeed;
}
Notice that these member variables are declared using the public access modifier. Public
members of a class are directly accessible once an object of this type has been created. As you may
already know, the term“object” is used to represent an instance of a given class type created using
the new keyword.
nNote Field data of a class should seldom (if ever) be defined as public. To preserve the integrity of your state
data, it is a far better design to define data as private (or possibly protected) and allow controlled access to the
data via type properties (as shown later in this chapter). However, to keep this first example as simple as possible,
public data fits the bill.
After you have defined the set of member variables that represent the state of the type, the next
design step is to establish the members that model its behavior. For this example, the Car class will
define one method named SpeedUp() and another named PrintState():
class Car
{
// The 'state' of the Car.
public string petName;
public int currSpeed;
// The functionality of the Car.
public void PrintState()
{
Console.WriteLine("{0} is going {1} MPH.", petName, currSpeed);
}
public void SpeedUp(int delta)
{
currSpeed += delta;
}
}
As you can see, PrintState() is more or less a diagnostic function that will simply dump the
current state of a given Car object to the command window. SpeedUp() will increase the speed of the
Car by the amount specified by the incoming int parameter. Now, update your Main() method with
the following code:
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Class Types *****\n");
// Allocate and configure a Car object.
Car myCar = new Car();
myCar.petName = "Henry";
myCar.currSpeed = 10;
// Speed up the car a few times and print out the
// new state.
for (int i = 0; i <= 10; i++)
{
myCar.SpeedUp(5);
myCar.PrintState();
}
Console.ReadLine();
}
Allocating Objects with the new Keyword
As shown in the previous code example, objects must be allocated into memory using the new keyword.
If you do not make use of the new keyword and attempt to make use of your class variable in a
subsequent code statement, you will receive a compiler error:
static void Main(string[] args)
{
// Error! Forgot to use 'new'!
Car myCar;
myCar.petName = "Fred";
}
To correctly create a class type variable, you may define and allocate a Car object on a single
line of code:
static void Main(string[] args)
{
Car myCar = new Car();
myCar.petName = "Fred";
}
As an alternative, if you wish to define and allocate an object on separate lines of code, you
may do so as follows:
static void Main(string[] args)
{
Car myCar;
myCar = new Car();
myCar.petName = "Fred";
}
Here, the first code statement simply declares a reference to a yet-to-be-determined Car object.
It is not until you assign a reference to an object via the new keyword that this reference points to a
valid class instance in memory.
In any case, at this point we have a trivial class type that defines a few points of data and some
basic methods. To enhance the functionality of the current Car type, we need to understand the role
of class constructors.
Thursday, October 22, 2009
Subscribe to:
Post Comments (Atom)
hi,
ReplyDeleteFirst of all. Thanks very much for your useful post.
I just came across your blog and wanted to drop you a note telling you how impressed I
was with the information you have posted here.
Please let me introduce you some info related to this post and I hope that it is useful
for .Net community.
There is a good C# resource site, Have alook
http://www.csharptalk.com/2009/09/c-class.html
http://www.csharptalk.com
simi