Partager via


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).

The following example shows an instance constructor:

class CoOrds
{
    public int x, y;

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

Note

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:

// 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 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:

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.

Example 1

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 (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:
        Console.WriteLine("CoOrds #1 at {0}", p1);
        Console.WriteLine("CoOrds #2 at {0}", p2);
        Console.ReadKey();
    }
}
/* Output:
 CoOrds #1 at (0,0)
 CoOrds #2 at (5,3)        
*/

Example 2

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 person = new Person();

        Console.WriteLine("Name: {0}, Age: {1}", person.name, person.age);
        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
// Output:  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).

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.

abstract class Shape
{
    public const double pi = 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);

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

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    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).

See Also

Reference

Classes and Structs (C# Programming Guide)

Constructors (C# Programming Guide)

Destructors (C# Programming Guide)

static (C# Reference)

Concepts

C# Programming Guide