Constructors in C #
Constructors in C #
In this article I will explain the constructor concept in C# along with practical demonstration which will help
What is constructor?
Default Constructor
Parameterized constructor
Private Constructor
Static Constructor
Copy Constructor
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);
}
}
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 constructo
of the class with some legal values.
Parameterized constructor
Constructor that accepts arguments is known as parameterized constructor. There may be situations, wher
members of different objects with different values when they are created. Parameterized constructors help
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();
}
}
}
Private Constructor
Private constructors are used to restrict the instantiation of object using 'new' operator. A private construc
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 construct
We have to take help of nested class (Inner Class) or static method to initialize a class having private const
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace private_constructor
{
class Program
{
class c1
{
int a, b;
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 pr
c1 ob1 = c1.create_instance();
ob1.display();
Console.ReadLine();
}
}
}
Static Constructors
C# supports two types of constructor, a class constructor static constructor and an instance constructor (no
Static constructors might be convenient, but they are slow. The runtime is not smart enough to optimize th
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.
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();
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.
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 define
c1 ob2 = new c1(ob1);
ob2.display();
Console.ReadLine();
}
}
}
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 execut
to execute must be put in the constructor. The general form of a C# constructor is as follows
The modifiers can be private,public, protected or internal.The name of a constructor must be the name of t
can take zero or more arguments. A constructor with zero arguments (that is no-argument) is known as de
not return type for a constructor.
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.
That is when we create the object of the class Complex, it automatically calls the constructor and initializes
that constructor is mainly used for initializing an object. Even it is possible to do very complicated calculatio
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
Remember that if we provide our own constructor, C# do not provide the default constructor.
// C# constructor example
// Author: [email protected]
using 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 mus
and/or type of arguments and/or order of arguments.
// C# constructor overloading
// author: [email protected]
using 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");
}
}
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 c
is not possible other classes to derive from this class or create an instance of this class. Private constructor
contain only static members. However a class can contain both private and public constructor and objects o
not by using the private constructor.
However the following program do not compile since it contain only private constructors
Constructor Chaining
The entire above program shows that C# supports constructor overloading. In C#, even one constructor ca
class or in the base class of this class. This is what is known as constructor chaining.A special type of synta
follows.
// C# constructor chaining
// Author: [email protected]
using 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 s
invokes the Complex() constructor.
Static Constructors
The normal constructors, which we explained till now, can be used for the initialization of both static and no
special type of constructor known as static constructor to initialize the static data members when the class
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 static constructor from the normal constructors. The static constructor can't take any arguments. That m
constructor, without any arguments. In other way it is not possible to overload a static constructor.
For example
// C# static constructor
// Author: [email protected]
using System;
class Complex
{
static Complex()
{
Console.WriteLine("static constructor");
}
}
class MyClient
{
public static void Main()
{
Complex c;
Console.WriteLine("RAJESH");
c = new Complex();
}
}
Note that static constructor is called when the class is loaded at the first time. However we can't predict the
constructor execution. They are called before an instance of the class is created, before a static member is
the derived class is called.
Like non-static constructors, static constructors can't be chained with each other or with other non-static co
base class is not inherited to the derived class.
Both static and non-static constructors are not inherited to a derived class from a base class. However, a de
a base class non-static constructor by using a special function base(). It is possible to invoke both default a
class from the derived class. If we don't call the base class constructor explicitly, the derived class construc
base class implicitly when an object of the derived class is created. This is shown in the program given belo
We can also call a base class constructor explicitly by using base() as shown below.
Destructors
The .NET framework has an in built mechanism called Garbage Collection to de-allocate memory occupied b
implements the statements to be executed during the garbage collection process. A destructor is a function
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
error.Also destructor will come in only one form, without any arguments. There is no parameterized destruc
Destructors are invoked automatically and can't be invoked explicitly. An object becomes eligible for garbag
the active part of the program. Execution of destructor may occur at any time after the instance or object b
In C# all classes are implicitly derived from the super base class object. The object class contains one spec
can override. The Garbage Collection mechanism in .NET will call this method prior to the garbage collection
when we provide a destructor in a class, during the compilation time, the compiler automatically generates
destructor and overridden Finalize() method can't co-exist in a class. The following code will generate a com
program
class Complex
{
~Complex()
{
}
protected override void Finaliz()
{
}
}
First, this writing concentrates of and compares between three programming languages, C#, C++/CLI, an
every developer should keep in mind while working with constructors, destructors, and finalizers and class h
class BaseClass
{
}
{
public DerivedClass()
{
}
{
}
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();
}
class BaseClass
{
{
}
{
}
{
}
When you define a class destructor with that C++-alike syntax (preceding the function name with a ~) the
with an override of the virtual Object.Finalize() function. That is, before the object is removed (i.e. GC-coll
destructor) is called first. This finalizer first executes your code. After that it calls the finalizer of the base
our assembly, we would see that our destructor in the ChildClass (so other classes) has been replaced with
protected virtual void Finalize()
{
try
{
Console.WriteLine("dtor of ChildClass");
}
finally
{
base.Finalize();
}
}
static void Main()
{
ChildClass cls = new ChildClass();
// 'cls' is removed from memory here
}
struct MyStruct
{
~MyStruct()
{
Console.WriteLine("dtor of MyStruct");
}
}
The code won't compile. That's because that GC doesn't handle structures.
public:
DerivedClass()
{
}
~DerivedClass()
{
GC::ReRegisterForFinalize(this);
}
};
public:
ChildClass()
{
}
}
{
}
};
Foo() of BaseClass
In classic C++, the overload of the function of the class being constructed is called unlike C# and MC++ (.N
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.
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.
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.
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);
}
}
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.
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);
}
}
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();
}
}