Export (0) Print
Expand All

Instance Constructors (C# Programming Guide)

Instance constructors are used to create and initialize instances. The class constructor is invoked when you create a new object, for example:

class CoOrds
{
    public int x, y;

    // constructor
    public CoOrds()
    {
        x = 0;
        y = 0;
    }
}

NoteNote

For clarity, this class contains public data members. This 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 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:

// A constructor with two arguments:
public CoOrds(int x, int y)
{
    this.x = x;
    this.y = y;
}

This allows CoOrd objects to be created with default or specific initial values, like this:

CoOrds p1 = new CoOrds();
CoOrds p2 = new CoOrds(5, 3);

If a class does not have a default constructor, one 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:

class Circle : Shape
{
    public Circle(double radius)
        : base(radius, 0)
    {
    }
}

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 a class with two class constructors, one without arguments and one with two arguments.

class CoOrds
{
    public int x, y;

    // Default constructor:
    public CoOrds()
    {
        x = 0;
        y = 0;
    }

    // A constructor with two arguments:
    public CoOrds(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    // Override the ToString method:
    public override string ToString()
    {
        return (System.String.Format("({0},{1})", x, y));
    }
}

class MainClass
{
    static void Main()
    {
        CoOrds p1 = new CoOrds();
        CoOrds p2 = new CoOrds(5, 3);

        // Display the results using the overriden ToString method:
        System.Console.WriteLine("CoOrds #1 at {0}", p1);
        System.Console.WriteLine("CoOrds #2 at {0}", p2);
    }
}

CoOrds #1 at (0,0)

CoOrds #2 at (5,3)

In this example, the class Person does not have any constructors, in which case, a default constructor is automatically provided and the fields are initialized to their default values.

public class Person
{
    public int age;
    public string name;
}

class TestPerson
{
    static void Main()
    {
        Person p = new Person();

        System.Console.Write("Name: {0}, Age: {1}", p.name, p.age);
    }
}

Name: , Age: 0

Notice that the default value of age is 0 and the default value of name is null. For more information on default values, see Default Values Table (C# Reference).

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.

abstract class Shape
{
    public const double pi = System.Math.PI;
    protected double x, y;

    public Shape(double x, double y)
    {
        this.x = x;
        this.y = y;
    }

    public abstract double Area();
}

class Circle : Shape
{
    public Circle(double radius)
        : base(radius, 0)
    {
    }
    public override double Area()
    {
        return pi * x * x;
    }
}

class Cylinder : Circle
{
    public Cylinder(double radius, double height)
        : base(radius)
    {
        y = height;
    }

    public override double Area()
    {
        return (2 * base.Area()) + (2 * pi * x * y);
    }
}

class TestShapes
{
    static void Main()
    {
        double radius = 2.5;
        double height = 3.0;

        Circle ring = new Circle(radius);
        Cylinder tube = new Cylinder(radius, height);

        System.Console.WriteLine("Area of the circle = {0:F2}", ring.Area());
        System.Console.WriteLine("Area of the cylinder = {0:F2}", tube.Area());
    }
}

Area of the circle = 19.63

Area of the cylinder = 86.39

For more examples on invoking the base class constructors, see virtual (C# Reference), override (C# Reference), and base (C# Reference).

Community Additions

ADD
Show:
© 2014 Microsoft