Wednesday 2 September 2020

C# constructor in easy way

 

Constructor:

A special method of the class that is automatically invoked when an instance of the class is created is called a constructor. The main use of constructors is to initialize the private fields of the class while creating an instance for the class. When you have not created a constructor in the class, the compiler will automatically create a default constructor of the class. The default constructor initializes all numeric fields in the class to zero and all string and object fields to null.

 

A constructor is a special method that is used to initialize an object. A constructor is invoked at the time of an object creation. Constructor name must be the same as its class name. A constructor must have no explicit return type.

 

Some of the key points regarding constructor are

  • A class can have any number of constructors.
  • A constructor doesn't have any return type, not even void.
  • A static constructor can not be a parametrized constructor.
  • Within a class, you can create one static constructor only. 

·       Different between Constructors and Method

Constructor

 Method

A constructor is used to initialize an object

A method is used to expose the behavior of an object

The constructor must not have a return type.

The method has or not have a return type.

A constructor must be the same as the class name

Method name may or may not be same as the class name

A constructor is invoked implicitly.

A method is invoked explicitly.

 

In C#, constructors can be divided into 5 types

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor
  4. Static Constructor
  5. Private Constructor 

Now, let's see each constructor type with the example below.

 

Default Constructor in C#

 

A constructor without any parameters is called a default constructor. If we do not create constructor the class will automatically call default constructor when an object is created.

A constructor without any parameters is called a default constructor; in other words, this type of constructor does not take parameters. The drawback of a default constructor is that every instance of the class will be initialized to the same values and it is not possible to initialize each instance of the class with different values. The default constructor initializes: 

  1. All numeric fields in the class to zero.
  2. All string and object fields to null.

Example

1.  using System;  

  1. namespace DefaultConstractor  

3.  {  

  1.     class addition  

5.      {  

  1.         int a, b;   

7.          public addition()   //default contructor  

  1.         {  

9.              a = 100;  

  1.             b = 175;  

11.                 }  

  1.    

13.                 public static void Main()  

  1.         {  

15.                     addition obj = new addition(); //an object is created , constructor is called  

  1.             Console.WriteLine(obj.a);  

17.                     Console.WriteLine(obj.b);  

  1.             Console.Read();  

19.                 }  

  1.     }  

21.         }  

Now run the application, the output will be as following:

 

 

Parameterized Constructor in C#

 

A constructor with at least one parameter is called a parameterized constructor. The advantage of a parameterized constructor is that you can initialize each instance of the class with a different value.

1.  using System;  

  1. namespace Constructor  

3.  {  

  1.     class paraconstrctor  

5.      {  

  1.       public  int a, b;  

7.        public paraconstrctor(int x, int y)  // decalaring Paremetrized Constructor with ing x,y parameter  

  1.         {  

9.              a = x;  

  1.             b = y;  

11.                 }  

  1.    }  

13.             class MainClass  

  1.     {  

15.                 static void Main()  

  1.         {  

17.                     paraconstrctor v = new paraconstrctor(100, 175);   // Creating object of Parameterized Constructor and ing values   

  1.             Console.WriteLine("-----------parameterized constructor example by vithal wadje---------------");  

19.                     Console.WriteLine("\t");  

  1.             Console.WriteLine("value of a=" + v.a );  

21.                     Console.WriteLine("value of b=" + v.b);  

  1.             Console.Read();  

23.                 }  

  1.     }  

25.         }  

Now run the application, the output will be as following:

 

 

 

Copy Constructor in C#

 

The constructor which creates an object by copying variables from another object is called a copy constructor. The purpose of a copy constructor is to initialize a new instance to the values of an existing instance.

 

Syntax

1.  public employee(employee emp)  

  1. {  

3.      name=emp.name;  

  1.     age=emp.age;  

5.  }  

The copy constructor is invoked by instantiating an object of type employee and bypassing it the object to be copied.

 

Example

1.  employee emp1=new  employee (emp2);  

Now, emp1 is a copy of emp2. 

 

Let's see its practical implementation.

1.  using System;  

  1. namespace copyConstractor  

3.  {  

  1.     class employee  

5.      {  

  1.         private string name;  

7.          private int age;  

  1.         public employee(employee emp)   // declaring Copy constructor.  

9.          {  

  1.             name = emp.name;  

11.                     age = emp.age;  

  1.         }  

13.                 public employee(string name, int age)  // Instance constructor.  

  1.         {  

15.                     this.name = name;  

  1.             this.age = age;  

17.                 }  

  1.         public string Details     // Get deatils of employee  

19.                 {  

  1.             get  

21.                     {  

  1.                 return  " The age of " + name +" is "+ age.ToString();  

23.                     }  

  1.         }  

25.             }  

  1.     class empdetail  

27.             {  

  1.         static void Main()  

29.                 {  

  1.             employee emp1 = new employee("Vithal", 23);  // Create a new employee object.  

31.                     employee emp2 = new employee(emp1);          // here is emp1 details is copied to emp2.  

  1.             Console.WriteLine(emp2.Details);  

33.                     Console.ReadLine();  

  1.         }  

35.             }  

  1. }  

Now run the program, the output will be as follows:

 

 

Static Constructor in C#

 

When a constructor is created using a static keyword, it will be invoked only once for all of the instances of the class and it is invoked during the creation of the first instance of the class or the first reference to a static member in the class. A static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.

 

Some key points of a static constructor are: 

  1. A static constructor does not take access modifiers or have parameters.
  2. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  3. A static constructor cannot be called directly.
  4. The user has no control over when the static constructor is executed in the program.
  5. A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

Syntax

1.  class employee  

  1.  {// Static constructor  

3.    static employee(){}  

  1.  }  

Now let's see it practically.

1.  using System;  

  1. namespace staticConstractor  

3.  {  

  1.     public class employee  

5.      {  

  1.         static employee() // Static constructor   

7.          declaration{Console.WriteLine("The static constructor ");  

  1.     }  

9.      public static void Salary()  

  1.     {  

11.                 Console.WriteLine();  

  1.         Console.WriteLine("The Salary method");  

13.             }  

  1. }  

15.         class details  

  1. {  

17.             static void Main()  

  1.     {  

19.                 Console.WriteLine("----------Static constrctor example by vithal wadje------------------");  

  1.         Console.WriteLine();  

21.                 employee.Salary();  

  1.         Console.ReadLine();  

23.             }  

  1.   }  

25.         }  

Now run the program the output will be look as in the following:

 

 

Private Constructor in C#

 

When a constructor is created with a private specifier, it is not possible for other classes to derive from this class, neither is it possible to create an instance of this class. They are usually used in classes that contain static members only. Some key points of a private constructor are:

  1. One use of a private constructor is when we have only static members.
  2. It provides an implementation of a singleton class pattern
  3. Once we provide a constructor that is either private or public or any, the compiler will not add the parameter-less public constructor to the class.

Now let's see it practically.

1.  using System;  

  1. namespace defaultConstractor  

3.  {  

  1.     public class Counter  

5.      {  

  1.         private Counter()   //private constrctor declaration  

7.          {  

  1.         }  

9.          public static int currentview;  

  1.         public static int visitedCount()  

11.                 {  

  1.             return ++ currentview;  

13.                 }  

  1.     }  

15.             class viewCountedetails  

  1.     {  

17.                 static void Main()  

  1.         {  

19.                     // Counter aCounter = new Counter();   // Error  

  1.             Console.WriteLine("-------Private constructor example by vithal wadje----------");  

21.                     Console.WriteLine();  

  1.             Counter.currentview = 500;  

23.                     Counter.visitedCount();  

  1.             Console.WriteLine("Now the view count is: {0}", Counter.currentview);  

25.                     Console.ReadLine();  

  1.         }  

27.             }  

  1. }  

Now run the application. The output is as follows.

 

 

If you uncomment the preceding statement that is commented in the above program then it will generate an error because the constructor is inaccessible (private).

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