A
constructor is a class member function that has the same name as the
class itself. It is a specialized method in a class (or struct) which
is invoked automatically when an instance (object) of the class (or
struct) is created. A class (or struct) may have multiple
constructors that take different arguments. A constructor cannot have
a return type not even void.
Constructors enable the programmer to set default values (initialization of all member variables), limit instantiation, and write code that is flexible and easy to read.
Constructors enable the programmer to set default values (initialization of all member variables), limit instantiation, and write code that is flexible and easy to read.
Types
of constructors:
- Class Constructors
- Instance Constructors
- Default Constructor
- Parametrized constructor
- Private Constructors
- Static Constructors
- Struct Constructors
Note:
C# does not provide a copy constructor for objects.
Instance
Constructors
Instance
constructors are used to create and initialize instances. The class
constructor is invoked when you create a new object.
Ex:
Point myPoint = new Point();
Point()
,
and another constructor with arguments (parametrized constructors),
such as Point(int
x, int y)
.If the class does not have a constructor, a default parameterless constructor is automatically generated and the default values are used to initialize the object fields (ex, an int is initialized to 0).
The class constructor can invoke the constructor of the base class through the initializer (base). Ex:
public Cylinder(double radius, double height): base(radius, height)
{ }
Here, the fields, radius
and height
,
are initialized through the base class constructor.
The class constructor can also invoke another constructor from the same class by using the keyword this. Ex:
public
Point(): this(0,20)
{ }
Here,
the parameterless constructor
Point()
invokes
another constructor that has two arguments to initialize the default
position at (0, 20).
Example1:
The following example demonstrates a class with two class
constructors, one without arguments (default constructor) and one
with two arguments (parametrized constructor).
//
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
Base: The base keyword is useful if we need to add a constructor to the derived class. This will have the derived class constructor invoke the base class constructor — with the specified argument. This: Since a class can have multiple constructors, this keyword is used to have one constructor invocation call another constructor.
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
Private Constructors
A
private constructor is a special instance constructor. It is commonly
used in classes that contain static members only. If a class has one
or more private constructors and no public constructors, then other
classes (except nested classes) are not allowed to create instances
of this class.
class NLog { // Private Constructor: private NLog() {} public static double e = 2.71828; }The declaration of the empty constructor prevents the automatic generation of a default constructor. Note that if you don't use an access modifier with the constructor it will still be private by default. However, the private modifier is usually used explicitly to make it clear that the class cannot be instantiated.
Private
constructors are useful to prevent creation of a class when there are
no instance fields or methods, such as the Math class, or when a
method is called to obtain an instance of a class.
Example:
The following is an example of a
class using a private constructor.
// PrivateCtor1.cs using System; public class MyClass { private MyClass() {} public static int counter; public static int IncrementCounter() { return ++counter; } } class MainClass { static void Main() { // If you uncomment the following statement, it will generate // an error because the constructor is inaccessible: // MyClass myObject = new MyClass(); // Error MyClass.counter = 100; MyClass.IncrementCounter(); Console.WriteLine("New count: {0}", MyClass.counter); } } Output New count: 101 Notice that if you uncomment the following statement from the example, it will generate an error because the constructor is inaccessible due to its protection level: // MyClass myObject = new MyClass(); // error
Static Constructors
A static constructor is used to initialize a class. It is called automatically to initialize the class before the first instance is created or any static members are referenced.
- A static constructor does not take access modifiers or have parameters.
- A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
- A static constructor cannot be called directly.
- A class can have only one static constructor.
- The user has no control on when the static constructor is executed in the program.
- A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.
MyClass
has
a static constructor and one static member, MyMethod()
.
When MyMethod()
is
called, the static constructor is invoked to initialize the class.
// StaticCtor1.cs using System; class MyClass { // Static constructor: static MyClass() { Console.WriteLine("The static constructor invoked."); } public static void MyMethod() { Console.WriteLine("MyMethod invoked."); } } class MainClass { static void Main() { MyClass.MyMethod(); } }Output
The static constructor invoked. MyMethod invoked.
Struct Constructors
Struct
constructors are similar to class constructors, except for the
following differences:
- Structs cannot contain explicit parameterless constructors. Struct members are automatically initialized to their default values.
- A struct cannot have an initializer in the form: base (argument-list).
Point
struct.
// Structctor1.cs using System; public struct Point { public int x, y; // Constructor: 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() { // Initialize two points: Point p1 = new Point(); Point p2 = new Point(10,15); // Display the results using the overriden ToString method: Console.WriteLine("Point #1 (default initialization): {0}", p1); Console.WriteLine("Point #2 (explicit initialization): {0}", p2); } }
Output Point #1 (default initialization): (0,0) Point #2 (explicit initialization): (10,15)
Thanks for another fantastic post. The place else may just anybody get
ReplyDeletethat kind of information in such an ideal way of writing? I have a
presentation next week, and I am at the look for such info.
Concreting