| ||||||
| ||||||

InitializationGoals:
OverviewHere we discuss the various options available to initialize the instance fields of a class. Default valuesInstance fields of a class are set to default values when an object is created. The default value depends on the type of the field.
Numeric fields such as
Fields of type
Characters fields are set to the null character (often written
References are set to
Variable initializerInstance fields can be initialized inline, that is, at the point of declaration. The official name for this technique is 'variable initializer'.
Constructor
The most powerful initialization technique is to provide a constructor. A constructor is
a special method that is called automatically each time an object is created. The
definition of a constructor is similar to a regular method except for two small
differences: the name of the constructor must be the same as the name of the enclosing
class and no return type is allowed. The client code does not invoke the constructor
directly, instead the client creates objects using the
Constructor overloadingA class can supply multiple constructors with different parameter lists. It is even possible to write a constructor that takes no arguments. The no argument constructor is sometimes called the 'default constructor'. The client code chooses the constructor to call by passing the appropriate parameters when an object is created.
Constructor initializer
One constructor can call another constructor in the same class. The syntax is
Compiler generated constructorIf a class does not define any constructors, then the compiler automatically generates a constructor that takes no arguments and has an empty body. Conversely, if a class defines even one constructor, then the compiler assumes the class designer is taking control of construction and does not create a constructor. Initialization orderThe various initialization options are executed in a well defined order. First, all fields are set to their default values. Second, the variable initializers are executed in order of their declaration. Finally, the constructor is run. This material is excerpted from the Programming C# course offered by DevelopMentor. |