Instance Constructors (C# Programming Guide)

Instance constructors are used to create and initialize any instance member variables when you use the new expression to create an object of a class. To initialize a static class, or static variables in a non-static class, you must define a static constructor. For more information, see Static Constructors (C# Programming Guide).

For clarity, this class contains public fields. The use of public fields is not a recommended programming practice because it allows any method anywhere in a program unrestricted and unverified access to an object's inner workings. Data members should generally be private, and should be accessed only through class methods and properties.

This instance constructor is called whenever an object based on the CoOrds class is created. A constructor like this one, which takes no arguments, is called a default constructor. However, it is often useful to provide additional constructors. For example, we can add a constructor to the CoOrds class that allows us to specify the initial values for the data members:

If a class does not have a constructor, a default constructor is automatically generated and default values are used to initialize the object fields. For example, an int is initialized to 0. For more information on default values, see Default Values Table (C# Reference). Therefore, because the CoOrds class default constructor initializes all data members to zero, it can be removed altogether without changing how the class works. A complete example using multiple constructors is provided in Example 1 later in this topic, and an example of an automatically generated constructor is provided in Example 2.

Instance constructors can also be used to call the instance constructors of base classes. The class constructor can invoke the constructor of the base class through the initializer, as follows:

In this example, the Circle class passes values representing radius and height to the constructor provided by Shape from which Circle is derived. A complete example using Shape and Circle appears in this topic as Example 3.

The following example demonstrates using the base class initializer. The Circle class is derived from the general class Shape, and the Cylinder class is derived from the Circle class. The constructor on each derived class is using its base class initializer.