C# Tutorial - More on ClassesEvery class has the same defining layout: [access-modifier] class [identifier] [:base-class]
{
class-body
}
Where:
ConstructorsWhen a class is declared as in the following code, we only say that we want to have an instance of the class in our program. We have not yet created the class in program memory. Person Paul; To do this we must instantiate an instance of the class, this is done using the new keyword, as in the following code: Person Paul = new Person(); You can see that after the new keyword we called a method with the same name as the class. This is called its constructor. By calling this constructor, memory is allocated for the class, and we can now use it in our program, as in the next code sample. Person Paul = new Person(); String surname = "Smith"; Paul.setSurname( surname ); A constructor is a method that is invoked upon instantiation of a class. In C# these are known as "instance constructors". An instance constructor is a member that implements the actions required to initialize an instance of a class. A constructor is invoked when you use the new operator, or use the various methods of reflection to create an instance of a class. Defining the ConstructorEvery constructor has the same defining layout: [access-modifier] constructor_name (parameters)
{
// constructor body
}
Where:
A constructor can take zero or more arguments as parameters. A constructor with zero arguments (that is no-arguments) is known as a default constructor. A class can have more than one constructor, by giving each constructor a different set of parameters. This gives the user the ability to initialise the object in more than one way. The constructor body can be used to initialise the object into a known starting state. Writing the ConstructorIn, general, a constructor’s access modifier is public, this is because the class that is creating an instance of this class, needs to be able to access the constructor of the class. public Person()
{
. . .
}
DestructorsEach class also requires a destructor, this is the code that is called to clean up the object when it has been finished with. However, if you do not provide one, then the Garbage Collector will deal with freeing up the memory for you. Any object that you create in the class, should be deleted from the class as a general rule of thumb. A destructor is defined pretty much in the same way as a constructor, but has a tilde (~) in front of the method name. public ~Person()
{
. . .
}
Everything ElseApart from the constructor and destructor, the class body can contain as many attributes and methods as required. However, if a class is getting too large to work with, think about logically splitting it into smaller classes, or into smaller files using partial classes.
|