Understanding Constructors in .Net

Just like any modern language, .Net classes can have different type of constructors.

In this tutorial, we will examine all constructors’ possibilities and why should we use them.

Default Constructor:
public class Teacher
  {
      //No constructor here, the default constructor will be used
      public int Id { get; set; }
  }

If a class doesn’t contain an instance constructor, a default constructor is provided by the framework. The provided default constructor will always be a parameterless.

Private & Protected Constructors:
public class Student
 {
    //This class cannot be initialized from the outside world
     private Student():base()
     { }
 }

Private constructors should be used if you need to have a constructor without having it available to the rest of the world to use.

There are two reasons to want to have a private or protected constructor:

  1. When you need to call your object’s base constructor (ctor –chaining)
  2. When you are using factory method approach to creating yours object (typically using a static method)
Static Constructor:
public class Teacher
{
  public   static decimal Salary { get; set; }
    static Teacher()
    {
        //only one instance is created and returned to the caller,
        //regardless of how many times the class is used
        Salary = 50.000m;
    }
  
}

Static constructors are the only way to initialize static members before the object state is accessed. It's critical to understand that static constructors will only be called once regardless of how many time the instance is created

Pingbacks and trackbacks (1)+

Comments are closed