Reader Level:
ARTICLE

Complete scene of Constructors in C#

On August 19, 2009 Articles | C# Programming
This article explains about constructors in C#.I have explained with the different scenarios through coding. It covers all the applicable area of constructors in C#
  • 0
  • 0
  • 11889
Download Files:
 


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

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.

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);
    }

}

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();
    }

}

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();
    }

}

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 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()
    {
    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)
    {
        _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

Conclusion:

I have explained the constructors with the different scenarios. I hope that this article has given a good idea about the constructor. I have not covered few things in this article. I try to update this article with missed things. I expect your valuable comments and feedback about my article.

I have attached the code snippet of this article.

Senthilkumar

He has more than 6 years of experience in the software development. He has spent most of the times in web application development.He has sound knowledge in the  ASP.Net, C#, SQL Server, AJAX, XML...

  • 59rank
  • 1M readers
  • 1times
COMMENT USING

Trending up