Tuesday 7 January 2020

Constructor types in C# with example

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.
  1. public class Person
  2. {
  3. }
  4. public class Person
  5. {
  6.     public Person() // Default constructor added by user
  7.     {
  8.         // any code you can add here
  9.     }
  10. }
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.
different types of constructors in c#
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:
  1. public class Person
  2. {
  3.     public int Id { get; set; }
  4.     public string Name { get; set; }
  5.     public int Age { get; set; }
  6.     public Person(string name, int age)
  7.     {
  8.         this.Name = name;
  9.         this.Age = age;
  10.     }
  11. }  
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:
  1. public class Person
  2. {
  3.     public int Id { get; set; }
  4.     public string Name { get; set; }
  5.     public int Age { get; set; }
  6.     public Person() { }
  7.     public Person(string name)
  8.     {
  9.         this.Name = name;
  10.     }
  11.     public Person(string name, int age)
  12.     {
  13.         this.Name = name;
  14.         this.Age = age;
  15.     }
  16. }  
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
  1.     // user of different constructors
  2. var person1 = new Person();
  3. var person2 = new Person("Peter Parker");    
  4. 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:
  1. public class Person
  2. {
  3.     public int Id { get; set; }
  4.     public string Name { get; set; }
  5.     public int Age { get; set; }        
  6.     public Person(Person objPerson)
  7.     {
  8.         this.Id = objPerson.Id;
  9.         this.Name = objPerson.Name;
  10.         this.Age = objPerson.Age;
  11.     }
  12. }
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
  1. public class Person
  2. {
  3.     public int Id { get; set; }
  4.     public string Name { get; set; }
  5.     public int Age { get; set; }
  6.     public Person() { }
  7.     public Person(Person objPerson)
  8.     {
  9.         this.Id = objPerson.Id;
  10.         this.Name = objPerson.Name;
  11.         this.Age = objPerson.Age;
  12.     }
  13. }
Now we can create an object of person and then use the copy constructor to create another person object
  1. var person1 = new Person();
  2. person1.Name = "Peter Parker";
  3. person1.Age = 40;
  4. 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
  1. public class Person :ICloneable
  2. {
  3.     public int Id { get; set; }
  4.     public string Name { get; set; }
  5.     public int Age { get; set; }
  6.     public Person() { }
  7.     public object Clone()
  8.     {
  9.         return this.MemberwiseClone();
  10.     }
  11. }
We will achieve the same goal as to copy constructor:
  1. var person1 = new Person();
  2. person1.Name = "Peter Parker";
  3. person1.Age = 40;
  4. 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.
  • A static constructor does not take access modifiers or have parameters.
  • A class can only one static constructor
  • A static constructor cannot have any parameter, because we cannot pass the value in any way.
  • A class can have both instance and static construction in a single class
  • A static constructor cannot be called directly.
Let's create a static constructor in our person class:
  1. public class Person
  2. {      
  3.     public static string Name { get; set; }
  4.     public static int Age { get; set; }
  5.     static Person() {
  6.         Name = "Peter Parker";
  7.         Age = 40;
  8.     }
  9. }  
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:
  1. public class Person
  2. {      
  3.     public static string Name { get; set; }
  4.     public static int Age { get; set; }
  5.     private Person() { }
  6.     public static void Disply(string city)
  7.     {
  8.         Console.WriteLine(String.Format("{0} is {1} year old and living in {2}", Name, Age, city));
  9.     }
  10. }
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
  1. Person.Name = "Peter";
  2. Person.Age = 40;
  3. Console.WriteLine(Person.Name);
  4. Console.WriteLine(Person.Age);
  5. Person.Disply("New York");
  6. Console.ReadLine();

No comments:

Post a Comment

Baisic Useful Git Commands

  Pushing a fresh repository Create a fresh repository(Any cloud repository). Open terminal (for mac ) and command (windows) and type the be...