Constructor is a special method, having the same name as the class/struct. When an object of class or struct is created, its constructor is called, and they usually used to initialize the data members of the new object. There are different types of constructors which we will see in detail in this article, like, default constructor, parameterized constructor, copy constructor, static constructor and private constructor.
Default Constructor
Default constructor can refer to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors, and it don't have any parameter. Many languages like C++, compiler don't generate any default constructor but user has to add one without any parameter. Even in C# we can add a default constructor, in that case compiler will not generate any.
public class Person
{
}
public class Person
{
public Person() // Default constructor added by user
{
// any code you can add here
}
}
I below Person class example both are same, in first case compiler will create on default constructor and in second case user already created one, so compiler will not create any more.
Parameterized Constructor
A constructor having one or more parameters is called a parameterized constructor. If a class or struct have only parameterized constructor, to create an object of class/struct we need to pass all the parameters, otherwise we will get compilation error, let's see it with example:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
We added some properties to the person like Id, Name and Age and decided to initialize the value at the time of creating the object. Now the person class have only one constructor, accepting two parameter Name and Age. What will happen when we try to create an object without passing any parameter, will the compiler create a default constructor? No, let's see:
var person = new Person(); // compilation error
It will give error: 'Person' does not contain a constructor that takes 0 arguments. It proves, compiler will not create any default constructor once we add any constructor to our class/struct.
So how can we use this class:
var person = new Person("Peter Parker", 40);
Now the person will become spider-man because we created object by giving the name and age.
A class can have any number of constructor with different number of parameters, see this:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public Person() { }
public Person(string name)
{
this.Name = name;
}
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
It have three constructors, default (without any parameter), one parameter and two parameters, so we can create person object by using any of them, for example
// user of different constructors
var person1 = new Person();
var person2 = new Person("Peter Parker");
var person3 = new Person("Peter Parker", 40);
All are valid, so we can use any of them according to the need.
Copy Constructor
A constructor accepting same type of object as parameter, for example, a person class having a constructor accepting the person object as parameter, is called the copy constructor. A class cannot have only copy constructor, it need atleast one more constructor to create the object. Let's use our person class and create a copy constructor to understand:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public Person(Person objPerson)
{
this.Id = objPerson.Id;
this.Name = objPerson.Name;
this.Age = objPerson.Age;
}
}
Right now Person class have only one constructor which is the copy constructor, as I said, class cannot have only copy constructor because in that case we cannot create the object of the class to pass in it. Let's add one more constructor, we can add type of constructor, say, add a default constructor, so code will be
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public Person() { }
public Person(Person objPerson)
{
this.Id = objPerson.Id;
this.Name = objPerson.Name;
this.Age = objPerson.Age;
}
}
Now we can create an object of person and then use the copy constructor to create another person object
var person1 = new Person();
person1.Name = "Peter Parker";
person1.Age = 40;
var copiedPerson = new Person(person1);
Here we created a person1 and by using copy constructor created an other object copiedPerson. Might you will be asking yourself, why we need the copy constructor to clone an object, why cannot we do this by using the ICloneable
, you are are right, it's up to you
If you want to use cloning then see this simple example by using ICloneable
public class Person :ICloneable
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public Person() { }
public object Clone()
{
return this.MemberwiseClone();
}
}
We will achieve the same goal as to copy constructor:
var person1 = new Person();
person1.Name = "Peter Parker";
person1.Age = 40;
var copiedPerson = person1.Clone() as Person;
It's up to you which one would you like to use and why, please share the thought if you have any.
Static Constructor
A static constructor is used to initialize the static member data or to perform some action only once in the beginning. It is called automatically before the first instance is created or any static members are referenced.
Let's create a static constructor in our person class:
public class Person
{
public static string Name { get; set; }
public static int Age { get; set; }
static Person() {
Name = "Peter Parker";
Age = 40;
}
}
A static constructor can access only static properties and members.
Private Constructor
My first response was WHAAAAT, a private Constructor? If we will have only a private constructor, we cannot create instance of that class and cannot be inherited from that, right?
That's what the purpose of private constructor. In some cases we create a class which only have static members, so creating instance of this class is useless. To prevent to create instance of class we use the private constructors.
Let's go back to our Person class and see it with example:
public class Person
{
public static string Name { get; set; }
public static int Age { get; set; }
private Person() { }
public static void Disply(string city)
{
Console.WriteLine(String.Format("{0} is {1} year old and living in {2}", Name, Age, city));
}
}
Note all the members are static, means cannot be accessed by any instance object, that's why we add the private constructor so user cannot create any object of Person class, we can directly access all the property and methods on the class
Person.Name = "Peter";
Person.Age = 40;
Console.WriteLine(Person.Name);
Console.WriteLine(Person.Age);
Person.Disply("New York");
Console.ReadLine();
![]() |
Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
|
By Ali Adravi On 14 Feb, 18 Viewed: 2,729 |
Polymorphism is derived from two Latin words, 1. Poly means many 2. Marphose means forms. By using inheritance, a class can be used as many types, say we have a Person which may be a Professor, may be a Student, may be Clerk. So in this article we will see some example of Polymorphism. When we... By Hamden On 01 Jun 2013 Viewed: 4,548
Creating windows service in C# is really easy but when we need to create first time we face many problems so in this post we will try to learn everything about window service. In this article we will create a windows service which will run after a particular interval, and time should be... By Ali Adravi On 30 Apr 2013 Viewed: 8,610
C# the language, right from the very beginning is always supported covariance and contravariance but in most simple scenario, now in C# 4.0 we have full support of covariance and contravariance in all circumstances, generic interface and generic delegates, other C# types already support from first... By Ali Adravi On 29 Mar 2013 Viewed: 4,977
In C# there are different data type and they use some default value when we declare a variable. When we define a variable of type int or Int32 say int score; so what is the value of score, will it be null or zero, in the same way if we create a variable of type string/String what value it holds... By Ali Adravi On 27 Mar 2013 Viewed: 2,599
An enumeration type (also known an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable to make programming clear, understandable and manageable. There are ways of using, like how to use enum in switch and case statement,... By Hamden On 27 Mar 2013 Viewed: 4,525