Web
Analytics
Constructors in C# with demo - Tutorial

For Consultation : +91 9887575540

Stay Connected :

Constructors in C sharp

The syntax for declaring basic constructors is a method that has the same name as the containing class and that does not have any return type:

It’s not necessary to provide a constructor for your class. In general, if you don’t supply any constructor, the compiler will generate a default one behind the scenes. It will be a very basic constructor that just initializes all the member fields by their default values like int=0, string=null , bool=false etc

Constructors follow the same rules for overloading as other methods — that is, you can provide as many overloads to the constructor as you want, provided they are clearly different in signature:
There are 5 types of constructors in C#

  • Default Constructor
  •  Parameterized Constructor
  •  Copy Constructor
  •  Static Constructor
  •  Private Constructor

1.Default Constuctor :

Syntax:

Let ‘s take very simple example to demonstrate that how default constructor initialize the member variables by their default values

DefaultConstructorExample

  1.  Parameterized Constructor 

Note: If we defined non-zero argument constructor then C# compiler skip to call zero argument constructor and gives error if we declared zero argument object.

Let’s have a example

  1. Copy Constructor

A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance. Check below example for this

 4.Static Constructor

When we declared constructor as static it will be invoked only once for any number of instances of the class and it’s during the creation of first instance of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.

 Important Point

–      Static constructor will not accept any parameters because it is automatically called by CLR.

–      Static constructor will not have any access modifiers.

–      Static constructor will execute automatically whenever we create first instance of class

–      Only one static constructor will allowed. 

  1. Private Constructor

Private constructor is a special instance constructor used in a class that contains static member only. If a class has one or more private constructor and no public constructor then other classes is not allowed to create instance of this class this mean we can neither create the object of the class nor it can be inherit by other class. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.

 using System;

using System.Collections.Generic;

 

 

Select your currency