Constructor(s) in C#(CheckList)
Manmohan J Mundhra
Architect @ Wissen Infotech | Apps Integration, Tech Upgrade, Cloud Migration
Constructor(s) in C#(CheckList)
Private, Public, Static
Private : This make class not initialized using NEW keyword. Example- Singleton class.
Public : Any one can use this class or inherit.
Static : Both non static and static class can have static constructor. You only need to consider one thing, non-static fields are not initialized until you create instance of non static class.
Default or Implicit, Explicit
Default or Implicit : If no explicit constructor provided then runtime provide default constructor without any parameter and call it implicitly during class creation.
Explicit : In case we have multiple constructors with different parameter. We create explicit instance of the class by providing required parameter value or no parameter.
Parameter Less, Overloaded, Constructor for Dependency Injection (DI)
Two main uses of constructor parameter is —
- Pass data to class during initialization ,
- Pass class instances of other class to make classes loosely couple which helps to avoid breaking code changes.
We can add multiple constructor just like over loaded methods using different parameter.
Default constructor is usually declared with no parameter.
Calling Base Class Constructor
We can call Base Class Constructor in child class like the following -
public class MyExceptionClass : Exception
{
public MyExceptionClass(string message) : base(message)
{
//other stuff here
}
}
Above we are calling base class constructor using base keyword and passing parameter i.e. message
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
public employee(employee emp)
{
name=emp.name;
age=emp.age;
}
The copy constructor is invoked by instantiating an object of type employee and bypassing it the object to be copied.