Constructors in C #

40
Constructors in C-sharp In this article I will explain the constructor concept in C# along with practical demonstr understand it in a simple way. What is constructor? Constructor is used to initialize an object (instance) of a class. Constructor is a like a method without any return type. Constructor has same name as class name. Constructor follows the access scope (Can be private, protected, public, Internal an Constructor can be overloaded. Constructors generally following types : Default Constructor Parameterized constructor Private Constructor Static Constructor Copy Constructor The constructor goes out of scope after initializing objects. Default Constructor A constructor that takes no parameters is called a default constructor. When a class is initiated default constructor is called which provides default values to d You need not to define default constructor it is implicitly defined. Practical: Default Constructor using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace default_constructor { class Program { class c1 { int a, b; public c1()

Transcript of Constructors in C #

Page 1: Constructors in C #

Constructors in C-sharp

In this article I will explain the constructor concept in C# along with practical demonstration which will help you to understand it in a simple way.

What is constructor?

Constructor is used to initialize an object (instance) of a class. Constructor is a like a method without any return type. Constructor has same name as class name. Constructor follows the access scope (Can be private, protected, public, Internal and external). Constructor can be overloaded.

Constructors generally following types :

Default Constructor Parameterized constructor Private Constructor Static Constructor Copy Constructor

The constructor goes out of scope after initializing objects. 

Default Constructor 

A constructor that takes no parameters is called a default constructor. When a class is initiated default constructor is called which provides default values to different data members of the class.

You need not to define default constructor it is implicitly defined. 

Practical: Default Constructor 

 using System;using System.Collections.Generic;using System.Linq;using System.Text;

namespace default_constructor{class Program{class c1{int a, b;

public c1(){this.a = 10;this.b = 20;}

public void display(){Console.WriteLine("Value of a: {0}", a);Console.WriteLine("Value of b: {0}", b);

Page 2: Constructors in C #

}}

static void Main(string[] args){// Here when you create instance of the class default constructor will be called.c1 ob1 = new c1();ob1.display();Console.ReadLine();}}}

Note: In the above practical example if you don't create a constructor still there will be a default constructor, which will initialize the data members of the class with some legal values.

Parameterized constructor 

Constructor that accepts arguments is known as parameterized constructor. There may be situations, where it is necessary to initialize various data members of different objects with different values when they are created. Parameterized constructors help in doing that task.

Practical: Parameterized Constructor

 using System;using System.Collections.Generic;using System.Linq;using System.Text;

namespace parameterized_constructor{class Program{class c1{int a, b;

public c1(int x, int y){this.a = x;this.b = y;}

public void display(){Console.WriteLine("Value of a: {0}", a);Console.WriteLine("Value of b: {0}", b);}}

static void Main(string[] args){// Here when you create instance of the class parameterized constructor will be called.c1 ob1 = new c1(10, 20);ob1.display();Console.ReadLine();

Page 3: Constructors in C #

}}}

Private Constructor 

Private constructors are used to restrict the instantiation of object using 'new' operator.  A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. This type of constructors is mainly used for creating singleton object. If you don't want the class to be inherited we declare its constructor private. We can't initialize the class outside the class or the instance of class can't be created outside if its constructor is declared private.We have to take help of nested class (Inner Class) or static method to initialize a class having private constructor.

Practical: Private Constructor

 using System;using System.Collections.Generic;using System.Linq;using System.Text;

namespace private_constructor{class Program{

class c1{int a, b;

// Private constructor declared hereprivate c1(int x, int y){this.a = x;this.b = y;}

public static c1 create_instance(){return new c1(12, 20);}

public void display(){int z = a + b;Console.WriteLine(z);}}

static void Main(string[] args){// Here the class is initiated using a static method of the class than only you can use private constructorc1 ob1 = c1.create_instance();ob1.display();Console.ReadLine();}

Page 4: Constructors in C #

}}

Static Constructors 

C# supports two types of constructor, a class constructor static constructor and an instance constructor (non-static constructor).Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize them in the same way it can optimize inline assignments. Non-static constructors are inline and are faster. Static constructors are used to initializing class static data members. Point to be remembered while creating static constructor: 1. There can be only one static constructor in the class.2. The static constructor should be without parameters.3. It can only access the static members of the class.4. There should be no access modifier in static constructor definition.

Static members are preloaded in the memory. While instance members are post loaded into memory.Static methods can only use static data members. 

Practical: Static Constructor

 using System;using System.Collections.Generic;using System.Linq;using System.Text;

namespace static_eg{

class Program{

public class test{static string name;static int age;

static test(){Console.WriteLine("Using static constructor to initialize static data members"name = "John Sena";age = 23;}

public static void display(){Console.WriteLine("Using static function");Console.WriteLine(name);Console.WriteLine(age);}

}

static void Main(string[] args){test.display();

Page 5: Constructors in C #

Console.ReadLine();}}}

Copy Constructor 

If you create a new object and want to copy the values from an existing object, you use copy constructor.This constructor takes a single argument: a reference to the object to be copied. 

Practical: Copy Constructor

 using System;using System.Collections.Generic;using System.Linq;using System.Text;

namespace copy_constructor{

class Program{

class c1{int a, b;

public c1(int x, int y){this.a = x;this.b = y;}

// Copy construtor public c1(c1 a){this.a = a.a;this.b = a.b;}

public void display(){int z = a + b;Console.WriteLine(z);}}

static void Main(string[] args){c1 ob1 = new c1(10, 20);ob1.display();// Here we are using copy constructor. Copy constructor is using the values already defined with ob1c1 ob2 = new c1(ob1);ob2.display();Console.ReadLine();

Page 6: Constructors in C #

}}}

Copy constructor sets behavior during runtime. It is shallow copying. 

I would be glad to share my knowledge and waiting for your feedback to increase my knowledgebase.

A constructor can be used, where every time an object gets created and if we want some code to be executed automatically. The code that we want to execute must be put in the constructor. The general form of a C# constructor is as follows 

modifier constructor_name (parameters){//constructor body}

The modifiers can be private,public, protected or internal.The name of a constructor must be the name of the class, where it is defined. A constructor can take zero or more arguments. A constructor with zero arguments (that is no-argument) is known as default constructor. Remember that there is not return type for a constructor. 

The following class contains a constructor, which takes two arguments. 

class Complex{private int x;private int y;public Complex (int i, int j){x = i;y = j;}public void ShowXY (){Console.WriteLine(x + "i+" + y);}} 

The following code segment will display 20+i25 on the command prompt.  

Complex c1 = new Complex (20,25);c1.ShowXY (); // Displays 20+i25

That is when we create the object of the class Complex, it automatically calls the constructor and initializes its data members x and y. We can say that constructor is mainly used for initializing an object. Even it is possible to do very complicated calculations inside a constructor. The statement inside a constructor can throw exceptions also. 

If we don't provide a constructor with a class, the C# provides a default constructor with an empty body to create the objects of the class. Remember

Page 7: Constructors in C #

that if we provide our own constructor, C# do not provide the default constructor. 

The complete program is given below

// C# constructor example// Author: [email protected] System;class Complex{private int x;private int y;public Complex(int i, int j) // constructor with 2 arguments{x = i;y = j;}public void ShowXY(){Console.WriteLine(x +"i+" + y);}}class MyClient{public static void Main(){Complex c1 = new Complex(20,25);c1.ShowXY();}} 

Constructor Overloading  

Just like member functions, constructors can also be overloaded in a class. The overloaded constructor must differ in their number of arguments and/or type of arguments and/or order of arguments. 

The following program shows the overloaded constructors in action. 

// C# constructor overloading// author: [email protected] System;class Complex{public Complex(int i, int j) {Console.WriteLine("constructor with 2 integer arguemets");}public Complex(double i, double j) {Console.WriteLine("constructor with 2 double arguments");}public Complex(){Console.WriteLine("no argument constructor"); 

Page 8: Constructors in C #

}}class MyClient{public static void Main(){Complex c1 = new Complex(20,25);// displays 'constructor with 2 integer arguments'Complex c2 = new Complex(2.5,5.9); // displays 'constructor with 2 double arguments'Complex c3 = new Complex(); displays 'no argument constructor'}}

Private Constructors

We already see that, in C#, constructors can be declared as public, private, protected or internal. When a class declares only private constructors, it is not possible other classes to derive from this class or create an instance of this class. Private constructors are commonly used in classes that contain only static members. However a class can contain both private and public constructor and objects of such classes can also be created, but not by using the private constructor.

The following is a valid program in C# 

// C# constructor both private & public// Author: [email protected] System;class Complex{private Complex(int i, int j) {Console.WriteLine("constructor with 2 integer arguments");}public Complex(){Console.WriteLine("no argument constructor"); }}class MyClient{public static void Main(){Complex c3 = new Complex();}}

However the following program do not compile since it contain only private constructors 

// C# constructor only private. Will show compilation error.// Author: [email protected] System;class Complex{private Complex(){Console.WriteLine("no argument constructor"); 

Page 9: Constructors in C #

}}class MyClient{public static void Main(){Complex c3 = new Complex();}}public void Method1(){Console.WriteLine("Method of a non-abstract class");}} 

Constructor Chaining

The entire above program shows that C# supports constructor overloading. In C#, even one constructor can invoke another constructor in the same class or in the base class of this class. This is what is known as constructor chaining.A special type of syntax is used for constructor chaining as follows. 

// C# constructor chaining // Author: [email protected] System;class Complex{private Complex(){Console.Write("1"); }private Complex(int x):this(){Console.Write("2"); }public Complex(int x, int y):this(10){Console.Write("3"); }}class MyClient{public static void Main(){Complex c = new Complex(10,20); // Displays 123}} 

In the above program the Complex(int x, int y) invokes the Complex(int x) constructor by using a special syntax ':' this(arguments), which in turn invokes the Complex() constructor.

Static Constructors 

The normal constructors, which we explained till now, can be used for the initialization of both static and non-static members. But C# provides a

Page 10: Constructors in C #

special type of constructor known as static constructor to initialize the static data members when the class is loaded at first. Remember that, just like any other static member functions, static constructors can't access non-static data members directly.

The name of a static constructor must be the name of the class and even they don't have any return type. The keyword static is used to differentiate the static constructor from the normal constructors. The static constructor can't take any arguments. That means there is only one form of static constructor, without any arguments. In other way it is not possible to overload a static constructor.

We can't use any access modifiers along with a static constructor. 

For example

// C# static constructor// Author: [email protected] System;class Complex{static Complex(){Console.WriteLine("static constructor");}}class MyClient{public static void Main(){Complex c;Console.WriteLine("RAJESH");c = new Complex();}} 

The output of the above program is RAJESHstatic constructor  

Note that static constructor is called when the class is loaded at the first time. However we can't predict the exact time and order of static constructor execution. They are called before an instance of the class is created, before a static member is called and before the static constructor of the derived class is called. 

Like non-static constructors, static constructors can't be chained with each other or with other non-static constructors. The static constructor of a base class is not inherited to the derived class. 

Constructors & Inheritance 

Both static and non-static constructors are not inherited to a derived class from a base class. However, a derived class non-static constructor can call a base class non-static constructor by using a special function base(). It is possible to invoke both default and parameterized constructors of the base class from the derived class. If we don't call the base class constructor explicitly, the derived class constructor will call the default constructor of the base class implicitly when an object of the derived class is created. This is shown in the program given below.

// C# Implicit call of base class default constructor// Author: [email protected] using System; 

Page 11: Constructors in C #

class Base{public Base(){Console.WriteLine("base constructor");}}class Derived : Base{}class MyClient{public static void Main(){Derived d1 = new Derived();//Displays 'base constructor'}} 

We can also call a base class constructor explicitly by using base() as shown below.  

// C# Implicit call of base class default constructor // Author: [email protected] using System; class Base{public Base(){Console.WriteLine("BASE 1");}public Base(int x){Console.WriteLine("BASE 2");}}class Derived : Base{public Derived():base(10){Console.WriteLine("DERIVED CLASS");}}class MyClient{public static void Main(){Derived d1 = new Derived();//Displays 'base constructor'}}

This program outputsBASE2DERIVED CLASS  

Page 12: Constructors in C #

The base() can be used for chaining constructors in a inheritance hierarchy.

Destructors 

The .NET framework has an in built mechanism called Garbage Collection to de-allocate memory occupied by the un-used objects. The destructor implements the statements to be executed during the garbage collection process. A destructor is a function with the same name as the name of the class but starting with the character ~.

Example: 

class Complex{public Complex(){// constructor}~Complex(){// Destructor}}

Remember that a destructor can't have any modifiers like private, public etc. If we declare a destructor with a modifier, the compiler will show an error.Also destructor will come in only one form, without any arguments. There is no parameterized destructor in C#.

Destructors are invoked automatically and can't be invoked explicitly. An object becomes eligible for garbage collection, when it is no longer used by the active part of the program. Execution of destructor may occur at any time after the instance or object becomes eligible for destruction.

In C# all classes are implicitly derived from the super base class object. The object class contains one special method, Finalize(), which every class can override. The Garbage Collection mechanism in .NET will call this method prior to the garbage collection of the objects this class. Remember when we provide a destructor in a class, during the compilation time, the compiler automatically generates the Finalize() method. That means that a destructor and overridden Finalize() method can't co-exist in a class. The following code will generate a compilation error because of the above program 

class Complex {~Complex(){}protected override void Finaliz(){}}

First, this writing concentrates of and compares between three programming languages, C#, C++/CLI, and ISO/ANSI C++. It discusses 9 rules that every developer should keep in mind while working with constructors, destructors, and finalizers and class hierarchies:

Rule #1: Contrsuctors are called in descending order Rule #2: In C# lexicology, a destructor and a finalizer refer to the same thing Rule #3: Destructors are called in ascending order

Page 13: Constructors in C #

Rule #4: Finalizers are a feature of GC-managed objects only Rule #5: You cannot determine when finalizers would be called Rule #6: MC++ differs between destructors and finalizers Rule #7: In MC++ and classic C++, you can determine when destructors are called Rule #8: In MC++, destructors and finalizers are not called together Rule #9: Beware of virtual functions in constructors

Rule #1: Constructors are called in descending order

Rule #1: Constructors are called in descending order; starting from the root class and stepping down through the tree to reach the last leaf object that you need to instantiate. Applies to C#, MC++, and ANSI C++.

Let's consider a simple class hierarchy like this:

class BaseClass

{

    public BaseClass()

    {

        Console.WriteLine("ctor of BaseClass");

    }

}

class DerivedClass : BaseClass

{

    public DerivedClass()

    {

        Console.WriteLine("ctor of DerivedClass");

    }

}

class ChildClass : DerivedClass

{

    public ChildClass()

    {

Page 14: Constructors in C #

        Console.WriteLine("ctor of ChildClass");

    }

}

ChildClass inherits from DerivedClass, and DerivedClass, in turn, inherits from BaseClass.

When we create a new instance of ChildClass using a simple line like this:

static void Main(){    ChildClass cls = new ChildClass();}

The code outputs the following results:

ctor of BaseClass ctor of DerivedClass ctor of ChildClass

Rule #2: In C# lexicology, a destructor and a finalizer refer to the same thing

Rule #2: In C# lexicology, a destructor and a finalizer refer to the same thing;  the function called before the object is fully-removed from the memory (i.e. GC-collected). Applies to C# only.

Let's consider the same class hierarchy but with destructors:

class BaseClass

{

    public ~BaseClass()

    {

        Console.WriteLine("dtor of BaseClass");

    }

}

class DerivedClass : BaseClass

{

    public ~DerivedClass()

    {

Page 15: Constructors in C #

        Console.WriteLine("dtor of DerivedClass");

    }

}

class ChildClass : DerivedClass

{

    public ~ChildClass()

    {

        Console.WriteLine("dtor of ChildClass");

    }

}

When you define a class destructor with that C++-alike syntax (preceding the function name with a ~) the compiler actually replaces your destructor with an override of the virtual Object.Finalize() function. That is, before the object is removed (i.e. GC-collected) from the memory, the finalizer (i.e. destructor) is called first. This finalizer first executes your code. After that it calls the finalizer of the base type of your object. If we could decompile our assembly, we would see that our destructor in the ChildClass (so other classes) has been replaced with this function:

protected virtual void Finalize(){    try    {        Console.WriteLine("dtor of ChildClass");    }    finally    {        base.Finalize();    }}

Rule #3: Destructors are called in ascending order

Rule #3: Destructors are called in ascending order, starting from the leaf object that you need to instantiate and moving up through the tree to reach the very first base class of your object. In reverse of constructors calling order. Applies to C#, MC++, and ANSI C++.

Now, instantiate your class:

static void Main(){    ChildClass cls = new ChildClass();    // 'cls' is removed from memory here}

Page 16: Constructors in C #

the code should outputs the following results:

dtor of ChildClass dtor of DerivedClass dtor of BaseClass

Rule #4: Finalizers are a feature of GC-managed objects

Rule #4: Finalizers are a feature of GC managed objects (i.e. managed classes). removes the object from the memory (i.e. frees memory associated with).

Now, try to create a simple structure with a destructor:

struct MyStruct{    ~MyStruct()    {        Console.WriteLine("dtor of MyStruct");    }}

The code won't compile. That's because that GC doesn't handle structures.

Rule #5: You can't determine when finalizers would be called

That's because you don't know when the next garbage collection would occur, even if you performed a manual garbage collection (using System.GC.Collect() function) you won't know exactly when memory would be released. In addition, GC always delay releasing of finalizable object, it puts them in a special GC queue called freachable (pronounced ef-reachable, F stands for Finalize) queue.

Rule #6: MC++ differs between destructors and finalizers

Rule #6: MC++ differs between destructors and finalizers. That is, finalizers are called by GC, and destructors are called when you manually delete the object.

Let's consider the same example but in MC++:

ref class DerivedClass : BaseClass

{

public:

          DerivedClass()

          {

                   Console::WriteLine("ctor of DerivedClass");

          }

Page 17: Constructors in C #

          ~DerivedClass()

         {

                   Console::WriteLine("dtor of DerivedClass");

                   GC::ReRegisterForFinalize(this);

          }

};

ref class ChildClass : DerivedClass

{

public:

          ChildClass()

          {

                   Console::WriteLine("ctor of ChildClass");

          }

          ~ChildClass()

          {

                   Console::WriteLine("dtor of ChildClass");

                   GC::ReRegisterForFinalize(this);

          }

};

When we run the code:

int main(){          ChildClass^ cls = gcnew ChildClass();}

it outputs the following results:

ctor of BaseClass ctor of DerivedClass ctor of ChildClass

The destructors are not called. Why? Unlike C#, in MC++ there is a big difference between destructors and finalizers. As you know, the finalizer is

Page 18: Constructors in C #

called when the GC removes the object from the memory. Destructors, on the other hand, are called when you destroy the object yourself (e.g. use the delete keyword.)

Now, try to change the test code to the following:

int main()

{

          ChildClass^ cls = gcnew ChildClass();

          delete cls;

}

Run the code. Now, destructors are called.

Next, let's add finalizers to our objects. The code should be like the following:

ref class BaseClass

{

public:

          BaseClass()

          {

                   Console::WriteLine("ctor of BaseClass");

          }

          ~BaseClass()

          {

                   Console::WriteLine("dtor of BaseClass");

                   GC::ReRegisterForFinalize(this);

          }

          !BaseClass()

          {

                   Console::WriteLine("finz of BaseClass");

          }

Page 19: Constructors in C #

};

ref class DerivedClass : BaseClass

{

public:

          DerivedClass()

          {

                   Console::WriteLine("ctor of DerivedClass");

          }

          ~DerivedClass()

          {

                   Console::WriteLine("dtor of DerivedClass");

                   GC::ReRegisterForFinalize(this);

          }

          !DerivedClass()

          {

                   Console::WriteLine("finz of DerivedClass");

          }

};

ref class ChildClass : DerivedClass

{

public:

          ChildClass()

          {

                   Console::WriteLine("ctor of ChildClass");

          }

Page 20: Constructors in C #

          ~ChildClass()

          {

                   Console::WriteLine("dtor of ChildClass");

                   GC::ReRegisterForFinalize(this);

          }

          !ChildClass()

          {

                   Console::WriteLine("finz of ChildClass");

          }

};

As you see, the syntax of constructors, destructors, and finalizers are very similar.

Now, let's try the code:

int main()

{

          ChildClass^ cls = gcnew ChildClass();

}

GC would call finalizers and the code would outputs the following:

ctor of BaseClass ctor of DerivedClass ctor of ChildClass finz of ChildClass finz of DerivedClass finz of BaseClass

Rule #7: In MC++ and C++, you can determine when destructors are called

Now, try to destroy the object yourself:

int main()

{

          ChildClass^ cls = gcnew ChildClass();

          delete cls;

Page 21: Constructors in C #

}

The delete statement calls object destructors and removes the object from memory.

Or else, declare the object with stack-semantics:

int main(){          ChildClass cls;}

Now, destructors are called when the scope of the object ends.

Rule #8: In MC++, destructors and finalizers are not called together

Rule #8: In MC++, destructors and finalizers are not called together. Only destructors or finalizers are called. If you manually delete the object or you declare it with stack-semantics, destructors are called. If you leaved the object for GC to handle, finalizers are called.

Now try to run the code. The code should outputs the following results:

ctor of BaseClass ctor of DerivedClass ctor of ChildClass dtor of ChildClass dtor of DerivedClass dtor of BaseClass

Rule #9: Beware of virtual functions in constructors

Rule #9: Beware of virtual (overridable) functions in constructors. In .NET (C# and MC++,) the overload of the most derived object (the object to be instantiated) is called. In traditional C++ (ISO/ANSI C++,) the overload of the current object constructed is called.

Let's update our C# example:

class BaseClass

{

    public BaseClass()

    {

        Foo();

    }

    public virtual void Foo()

    {

        Console.WriteLine("Foo() of BaseClass");

    }

Page 22: Constructors in C #

}

class DerivedClass: BaseClass

{

    public DerivedClass()

    {

    }

    public override void Foo()

    {

        Console.WriteLine("Foo() of DerivedClass");

    }

}

class ChildClass : DerivedClass

{

    public ChildClass()

    {

    }

    public override void Foo()

    {

        Console.WriteLine("Foo() of ChildClass");

   }

}

When you execute the code:

static void Main(){    ChildClass cls = new ChildClass();}

Page 23: Constructors in C #

you would get the following results:

Foo() of ChildClass

The same code in MC++:

ref class BaseClass

{

public:

          BaseClass()

          {

                   Foo();

          }

          virtual void Foo()

          {

                   Console::WriteLine("Foo() of BaseClass");

          }

};

ref class DerivedClass : BaseClass

{

public:

          DerivedClass()

          {

          }

          virtual void Foo() override

          {

                   Console::WriteLine("Foo() of DerivedClass");

          }

Page 24: Constructors in C #

};

ref class ChildClass : DerivedClass

{

public:

          ChildClass()

          {

          }

          virtual void Foo() override

          {

                   Console::WriteLine("Foo() of ChildClass");

          }

};

The code outputs the same results.

But what if you need to call the virtual function of the BaseClass? Just change the code to the following:

ref class BaseClass

{

public:

          BaseClass()

          {

                   BaseClass::Foo();

          }

          virtual void Foo()

          {

                   Console::WriteLine("Foo() of BaseClass");

          }

Page 25: Constructors in C #

};

Now, the code outputs:

Foo() of BaseClass

Let's consider the same example but in classic ISO/ANSI C++:

class CBaseClass

{

public:

          CBaseClass()

          {

                   Foo();

          }

          virtual void Foo()

          {

                   cout << "Foo() of CBaseClass" << endl;

          }

};

class CDerivedClass : CBaseClass

{

public:

          CDerivedClass()

          {

          }

          virtual void Foo() override

          {

                   cout << "Foo() of CDerivedClass" << endl;

Page 26: Constructors in C #

          }

};

class CChildClass : CDerivedClass

{

public:

          CChildClass()

          {

          }

          virtual void Foo() override

          {

                   cout << "Foo() of CChildClass" << endl;

          }

};

Now, run the code. It should outputs:

Foo() of BaseClass

In classic C++, the overload of the function of the class being constructed is called unlike C# and MC++ (.NET in general.)

Introduction

The constructor plays significant role in the nay kind of programming language. Here I explained the types of constructor and its limitation with suitable examples. Let us see the constructor.

Constructors:

The constructor is a special method to the class and struts. This constructor is used to initialize the types and objects. The complier consider as constructor when the constructor have the same name as class name. Every class has the default constructor in the class (default constructor). Which can be called as implicit constructor. This can be used to define the default values the data types when there are not defined.

The user can use the default constructor for explicitly to create the instance of the classes.

Page 27: Constructors in C #

The constructor access modifier is public then it will be executed when the object is instantiated. The private constructor cannot be declaring. When object instantiate the outside class then it will throw an error like protection level. The internal also can be defined access modifier to the class constructor that will support up to that current assembly.

Limitations:

The constructor should have the same as the class or struct name. It cannot return any values to the calling program or function. It static constructor cannot have any parameters. It should have public or internal access modifiers. It can be declared as private but no

use of it. When we instantiate the object it must throw compilation error like inaccessible due to protection level.

It can be used to capture the parameters and initialize the values rather than do the complex logics.

Constructor: 

The simple constructor can be used to instantiate the object and define the data type values.

The syntax of the constructor is the following

access-modifier Class_Name(data type Parameter1,data type Parameter 2, [Classes Obj]){//Code here}

using System;public class SimpCons{    private int a;    private int b;    public SimpCons(int x, int y)    {        a = x;        b = y;        Display();    }    public void Display()    {        Console.WriteLine("The value of a is " + a);        Console.WriteLine("The value of b is " + b);    }}class SimpleConstructor{    public static void Main()    {        SimpCons oSimpCons = new SimpCons(5, 5);    }}

In the above code, the constructor is used to initialize the values to the variables.

Page 28: Constructors in C #

The constructor can be called the user defined the method in the both base and inherited class. Suppose I have not used the constructor then it will use the implicit constructor to initialize the values for the variables.

Overload Constructor

The constructor can be overloaded. As you know the constructor should be same as class name. But it can be overloaded just like method overloading. The same polymorphism concept can be applicable for the constructor. The same method name with different arguments.

Overload Constructor with different data types

The constructor can be overloaded with the same name of the constructor with different signature. The compiler only considers the signature type of the constructor. The arguments may be like int, string, char, float, double, etc..,

using System;class OverCons{    public OverCons()    {        Console.WriteLine("Hi! Welcome to Overload Constructor");        Console.WriteLine("-----------------------------------");    }    public OverCons(int a, int b)    {        Console.WriteLine("The addition of " + a + " and " + b + " is " + (a + b));    }    public OverCons(string str1, string str2)    {        Console.WriteLine("Your full name is " + (str1 + str2));    }}class ConstuctorOverload{    public static void Main(string[] args)    {        OverCons oOverCons = new OverCons();        OverCons oOverCons1 = new OverCons(90, 10);        OverCons oOverCons2 = new OverCons("Senthil", "kumar");    }}

This example shows there are three overloaded constructors. One is default constructor, second one is it accepts two integer values. Final constructor accepts the string. It can be any different combination of data types of parameter to the functions. It will not allow the constructor with the same signature types with different variable name. Because the compiler identifies the constructor based on the type of signature matches.

Overload Constructor with different class objects

When overload the constructors it accepts the different types of class objects. It can be overloaded with the objects.

Page 29: Constructors in C #

using System;using System.Collections;using System.Text;

class ObjOver{    public ObjOver(ArrayList oArrayList)    {        Console.WriteLine("Constructor - ArrayList");        Console.WriteLine("-----------------------");        for (int i = 0; i < oArrayList.Count; i++)        {            Console.WriteLine(oArrayList[i].ToString());        }    }    public ObjOver(Stack oStack)    {        Console.WriteLine("Constructor - Stack");        Console.WriteLine("-------------------");        foreach (string str in oStack)        {            Console.WriteLine(str);        }    }    public ObjOver(StringBuilder oSB)    {        Console.WriteLine("Constructor - StringBuilder");        Console.WriteLine("---------------------------");        Console.WriteLine(oSB.ToString());    }} 

class ObjOverCons{    public static void Main(string[] args)    {        ArrayList oArrayList = new ArrayList();        for (int i = 0; i < 10; i++)        {            oArrayList.Add(i);        }        Stack oStack = new Stack();        oStack.Push("Senthil");        oStack.Push("Kumar");        StringBuilder oSB = new StringBuilder();        oSB.Append("Welcome To Object Overload Constructor");        oSB.Append(Environment.NewLine);        oSB.Append("Sample programs developed by Erode Senthilkumar");        ObjOver oObjOver1 = new ObjOver(oArrayList);        ObjOver oObjOver2 = new ObjOver(oStack);        ObjOver oObjOver3 = new ObjOver(oSB);    }}

Page 30: Constructors in C #

Here the constructor has overloaded with the class objects. 

Private Constructor

The private constructor is a special method in the class. It can be only defined when the class has only the static members.

using System;public class StaticBase{    private StaticBase()    {        Console.WriteLine("Hi");    }    public static void Display()    {        Console.WriteLine("Display() method");    }}

class PrivateStatic{    public static void Main(string[] args)    {        StaticBase.Display();    }}

Here the below code cannot be executed. Here inherited class "DeriveCons" when try to access the properties of the "BaseCons" then the constructor method is defined as private access modifier. So it will throw exception like due to protection level.

using System; 

public class BaseCons{    private BaseCons()    {        Console.WriteLine("BaseCons Constructor");    }}public class DeriveCons : BaseCons{    public DeriveCons()    {        Console.WriteLine("DeriveCons - Constructor");    }}class PrivateCons{    public static void Main(string[] args)    {        DeriveCons oDeriveCons = new DeriveCons();    }}

Page 31: Constructors in C #

Static Constructor:

Used for initializing only the static members of the class. These will be invoked for the very first time the class is being loaded on the memory. They cannot accept any arguments. Static Constructors cannot have any access modifiers.

using System;class BaseStatic{    public static int i;    static BaseStatic()    {        i = 100;        Console.WriteLine("BaseStatic Constructor");        Console.WriteLine("i value is " + i);    }}class StaticCons{    public static void Main(string[] args)    {        Console.WriteLine("Static Constructor");        Console.WriteLine("------------------");        BaseStatic oBaseStatic = new BaseStatic();    }}

In the above example, the static constructor will allow us to initialize the values for that static variable. It will not allow to use any other type variable.

The below will throw an error. Because I have tried to initialize the non static variable.

using System;class BaseClass{    public static int i;    public int a = 0;    static BaseClass()    {        i = 10;        a = 15;    }    public void Print()    {        Console.WriteLine("The value of i is " + i);        Console.WriteLine("The value of a is " + a);    }}class StaticCons1{    public static void Main(string[] args)    {        BaseClass oBaseClass = new BaseClass();        oBaseClass.Print();

Page 32: Constructors in C #

    }}

Behavior of the Constructor in the Inheritance

As you know the constructor can call the method of the class. In the below mentioned code there are two classes. One is base class and another one is Derived class. The derived class inherited from the base class. In the main program we have instantiated the Derived class. The Base class has the virtual method name called Display. It has overridden in the Derived Class. If I instantiate the Derived class then which constructor will call first?

using System;public class BaseClass{    public string _ClassState;    public BaseClass()    {        _ClassState = "Base Class";        Console.WriteLine(_ClassState);        Display();    }    public virtual void Display()    {        Console.WriteLine("Base Class - Display()");    }}class DerivedClass : BaseClass{    public DerivedClass()    {        _ClassState = "Derived Class";        Console.WriteLine(_ClassState);    }    public override void Display()    {        Console.WriteLine("Derived Class - Display()");    }}class InherVirtualCons{    public static void Main(string[] args)    {        DerivedClass oDerivedClass = new DerivedClass();    }}

Yes! You are right!! The base class constructor will call first. Again I have called the method name in the Display. Actually I was expecting the base class Display method call first. But without call the Derived Class constructor it has called the Derived class Display method. In this scenario it considers only the current derived object method.

Exception Handling in the Constructors

The constructor will allow handling the exception. Before that we no need to write the more complex logics in the constructors. It has to be used to initialize the data types and create

Page 33: Constructors in C #

the object for the built in classes.

using System;class ConsExcep{    public ConsExcep(int numer, int dinom)    {        try        {            int Result = numer / dinom;            Console.WriteLine("Result is:" + Result);        }        catch (Exception oEx)        {            Console.WriteLine("Error :" + oEx.Message);        }    }}class ExcepConstructor{    public static void Main(string[] arsg)    {        ConsExcep oConsExcep = new ConsExcep(5, 0);    }}

Here it handles the divide by zero exception.

Constructor in Partial Class

As we know this partial class is the new feature from C# 2.0 onwards. The same class name can be divided into multiple classes with the same class name and different class file name along with partial keyword.

Here a class can have the constructor in the different file name. As we know while compilation the compiler will build the same class name in the different file as single code unit. 

using System;public partial class PartialClass{     public PartialClass()    {        Console.WriteLine("PartialClass Constructor");    }    public void Display()    {        Console.WriteLine("PartialClass - Display()");    }}public partial class PartialClass{    /*    public PartialClass()    {

Page 34: Constructors in C #

    Console.WriteLine("PartialClass Constructor1");    }    */    public PartialClass(string strName)    {        Console.WriteLine("Name: " + strName);    }    public void Print()    {        Console.WriteLine("PartialClass - Print()");    }}class PartialCons{    public static void Main(string[] args)    {        PartialClass oPartialClass = new PartialClass();        oPartialClass.Display();        oPartialClass.Print();        PartialClass oPartialClass1 = new PartialClass("Erode Senthilkumar");    }}

Here the example shows the same default signature cannot have more than once in the every class. Because it will became ambiguity method while compiler compile these files into the single unit. But we can load the constructor in the different signatures in the every partial class.

Constructors in Struct

The struct can have the constructors. But it differs from the classes. The struct is value type. It will be stored on the stack. We have seen that class can have the default constructor explicitly. But here stack will not allow writing the default constructor. It should contain the parameter. But we can overload the constructor in the struct. Every struct has the default implicit constructor. It will get execute internally to initialize the default value to the variables. . But we cannot have the default constructor with out any parameter in the struct like the following.

struct Employee{    public Employee()    {        Console.WriteLine("Default Constructor in struct");    }}

The struct should contain the constructor with the parameters like the following.

using System;struct structstudent{    private string _Sname;    private string _Class;    private string _Age;    public structstudent(string sname, string sclass, string sage)

Page 35: Constructors in C #

    {        _Sname = sname;        _Class = sclass;        _Age = sage;    }    public void PrintReport()    {        Console.WriteLine("Student Report");        Console.WriteLine("--------------");        Console.WriteLine("Student Name: " + _Sname);        Console.WriteLine("Student Class: " + _Class);        Console.WriteLine("Student Age: " + _Age);    }}class StructCons{    public static void Main(string[] args)    {        structstudent oSD = new structstudent("Rama", "1st Std", "6");        oSD.PrintReport();    }}

In the above struct is a valid one