Export (0) Print
Expand All
12 out of 15 rated this helpful - Rate this topic

Instance Constructors

Instance constructors are used to create and initialize instances. Constructors are declared using the following form:

[attributes] [modifiers] identifier([formal-parameter-list]) 
[initializer] { constructor-body }

where:

attributes (Optional)
Additional declarative information. For more information on attributes and attribute classes, see C# Attributes.
modifiers (Optional)
The allowed modifiers are extern and the four access modifiers.
identifier
The identifier is the same as the class name.
formal-parameter-list (Optional)
The optional parameters passed to the constructor. The parameters must be as accessible as the constructor itself.
initializer (Optional)
Invoked before the execution of the constructor body. The initializer can be one of the following with an optional argument-list:
: base (argument-list)
: this (argument-list)
constructor-body
The block that contains the statements that initialize the class instance.

Remarks

The class constructor is invoked when you create a new object, for example:

Point myPoint = new Point();

A class can have more than one constructor. For example, you can declare a constructor without arguments, such as Point(), and another constructor with arguments, such as Point(int x, int y).

If the class does not have a constructor, a default parameterless constructor is automatically generated for you and the 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.

The class constructor can invoke the constructor of the base class through the initializer, for example:

public Cylinder(double radius, double height): base(radius, height)
{
}

In the preceding example, the fields, radius and height, are initialized through the base class constructor. This is analogous to the C++ initialization list.

The class constructor can also invoke another constructor from the same class by using the keyword this, for example:

public Point(): this(0,20)
{
}

In the preceding example, the parameterless constructor Point() is invoking another constructor that has two arguments to initialize the default position at (0, 20).

Example 1

The following example demonstrates a class with two class constructors, one without arguments and one with two arguments.

// Constructor1.cs
using System;

class Point
{
   public int x, y;
   // Default constructor:
   public Point() 
   {
      x = 0;
      y = 0;
   }
   // A constructor with two arguments:
   public Point(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() 
   {
      Point p1 = new Point();
      Point p2 = new Point(5,3);

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

Output

Point #1 at (0,0)
Point #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.

// Constructor2.cs
using System;

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

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

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

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.

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.

// CtorInitializer.cs
using System;

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

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

   public abstract double Area();
}

class Circle: Shape 
{
   public Circle(double radius): base(radius,0,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 TestClass 
{
   public static void Main()  
   {
      double radius = 2.5, height = 3.0;
      Circle myCircle = new Circle(radius);
      Cylinder myCylinder = new Cylinder(radius, height);

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

Output

Area of the circle   = 19.63
Area of the cylinder = 86.39

For more examples on invoking the base class constructors, see virtual, override, and base.

See Also

10.10 Instance Constructors | Constructors and Destructors | Class Constructors

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.