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:
public class Student { public Student() { } //other class definition
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:
public Student() // zeroparameter constructor { // construction code } public Student(int rollnumber) // another overload { // construction code }
Let ‘s take very simple example to demonstrate that how default constructor initialize the member variables by their default values
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Constructors { class Program { static void Main(string[] args) { student s = new student(); Console.WriteLine("Roll Number=" + s.rollnumber + " Student Name =" + s.studentname + " Passed=" + s.passed); Console.ReadLine(); } } public class student { public int rollnumber; public string studentname; public bool passed; } }
- 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Constructors
{
class Program
{
static void Main(string[] args)
{
// student s = new student();//This Object will raise error of default or 0 argument constructor because we have specified only argument constructor.
//To resolve this issue we have to pass 0 argument constructor.or use only argument constructor like this
student s = new student(1,"yogesh",true);
Console.WriteLine("Roll Number=" + s.rollnumber + " Student Name =" + s.studentname + " Passed=" + s.passed);
Console.ReadLine();
}
}
public class student
{
public int rollnumber;
public string studentname;
public bool passed;
public student(int rno, string sname,bool p)
{
this.rollnumber = rno;
this.studentname = "yogesh";
this.passed = true;
}
}
}
- 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
using System;
namespace ConsoleApplication1{
class CopyExample
{
public string param1, param2;
public CopyExample (string x, string y)
{
param1 = x;
param2 = y;
}
public CopyExample (CopyExample obj) // Copy Constructor
{
param1 = obj.param1;
param2 = obj.param2;
}
}
class Program
{
static void Main(string[] args)
{
CopyExample obj = new CopyExample ("Welcome", "Yogesh"); // Create instance to class Sample
CopyExample obj1=new CopyExample (obj); // Here obj details will copied to obj1
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
}
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.
using System; namespace ConsoleApplication3 { class Sample { public string param1, param2; static Sample() { Console.WriteLine("Static Constructor"); } public Sample() { param1 = "Sample"; param2 = "Instance Constructor"; } } class Program { static void Main(string[] args) { // Here Both Static and instance constructors are invoked for first instance Sample obj=new Sample(); Console.WriteLine(obj.param1 + " " + obj.param2); // Here only instance constructor will be invoked Sample obj1 = new Sample(); Console.WriteLine(obj1.param1 +" " + obj1.param2); Console.ReadLine(); } } }
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.
- 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;
using System.Linq; using System.Text; using System.Threading.Tasks; namespace Constructors { class Program { static void Main(string[] args) { student.fathername = "sharma"; Console.WriteLine(student.fathername); student s = new student(1,"yogesh",true); Console.WriteLine("Roll Number=" + s.rollnumber + " Student Name =" + s.studentname + " Passed=" + s.passed); Console.ReadLine(); } } public class student { public int rollnumber; public string studentname; public bool passed; public static string fathername; public student(int rno, string sname,bool p) { this.rollnumber = rno; this.studentname =sname; this.passed =p; } private student() { Console.WriteLine("Private Construtor is called"); } } }