Constructors

Constructors initialize code on class or struct. Defined like methods except method name is same as class name with no return type defined. It initializes the data member of the new object.

//class
public class Panda
{
	//define field
	string name;

	//constructor with the parameter defined
	public Panda (string n)
	{
	   //initialization code and set up field
	   name = n;
	}
}
//Calling the constructor
Panda p = new Panda("Tommy");

//parameterless constructor
public class Taxi
{
    public bool isInitialized;
    public Taxi()
    {
        isInitialized = true;
    }
}

class TestTaxi
{
    static void Main()
    {
        Taxi t = new Taxi();
        Console.WriteLine(t.isInitialized);
    }
}

In this example, The Taxi class is instantiated with new operator then constructor is invoked after memory allocation.

The default constructor takes no parameter and gets invoked when the object is instantiated with new operator.

If the class is not static and no constructor is defined then the compiler assigns a default public constructor.

The class can be prevented by having a private constructor.

Structs cannot contain explicit constructors, compile provides one by default.

Constructors that take parameters must be called through a new statement or a base statement.

public class Employee
{
    public int salary;

    public Employee(int annualSalary)
    {
        salary = annualSalary;
    }

    public Employee(int weeklySalary, int numberOfWeeks)
    {
        salary = weeklySalary * numberOfWeeks;
    }
}

Employee e1 = new Employee(200);
Employee e2 = new Employee(6,9);

Classes and structs can also define multiple constructors, and neither is required to define a default constructor.

A constructor can use the base keyword to call the constructor of a base class.

namespace Rextester
{
    public class Program
    {
                
        public static void Main(string[] args)
        {
            Manager m = new Manager(200);
           
        } 
    }
    
    public class Manager : Employee
    {
        public Manager(int Salary) : base(Salary){}

    }
    
    public class Employee {
         
        public Employee(int Salary) { Console.WriteLine("Employee with param");}
    
    }
  
}

The base keyword can be used with or without parameters.

//With parameter
public Manager(int Salary) : base(Salary){}

//Without Parameter
public Manager(): base(){}

If a base-class constructor is not called explicitly by using the base keyword, the default constructor, if there is one, is called implicitly.

If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor by using base.

A constructor can invoke another constructor in the same object by using the this keyword.

namespace Rextester
{
    public class Program
    {
                
        public static void Main(string[] args)
        {
            Manager m = new Manager(200,5);
            Console.WriteLine(m.salary);
           
        } 
    }
    
    public class Manager
    {
        public int salary;
        public Manager(int Salary, int weeks) : this (Salary * weeks)
        {
           
        }
        
        public Manager(int annualsalary)
        {
           salary = annualsalary;
        }

    }
    
  
}

Instance Constructors

Instance constructors are used to create and initialize any instance member variables when you use the new expression to create an object of a class.

Instance constructors can also be used to call the instance constructors of base classes. The class constructor can invoke the constructor of the base class through the initializer.

Private Constructors

  • Used in classes that contain static members only.
  • Class with private constructors cannot create instances of the class.
  • Declaration of empty constructor prevents the generation of default constructor.
  • Default modifier for the constructor is private.
  • Private constructors are used to prevent creating instances of a class when there are no instance fields or methods.
  • If all the methods in the class are static, consider making the complete class static.
class NLog
{
    // Private Constructor:
    private NLog() { }

    public static double e = Math.E;  //2.71828...
}
using System;

namespace Rextester
{
    public class Program
    {
                
        public static void Main(string[] args)
        {
           Maths m = new Maths(10,5);
           //m.GetX();
           Console.WriteLine(m.GetX()); 
            
        } 
    }
    
    class Maths
    {
        //private default constructor - parameterless
        private Maths() {}
        
        //fields
        private int x ;
        private int y ;
        
        //public construtor with parameter
        public Maths(int x1, int y1)
        {
          x = x1;
          y = y1;  
        }
        
        //methods
        public int GetX()
        {
            return x;
        }
        
    }
  
}

Static Constructors

A static constructor is used to initialize any static data or perform action that needs to be performed only once and it is called automatically before the first instance.

class SimpleClass
{
	
    // Static variable that must be initialized at run time.
    static readonly long baseline;

    // Static constructor is called at most one time, before any
    // instance constructor is invoked or member is accessed.
    static SimpleClass()
    {
        baseline = DateTime.Now.Ticks;
    }
}

A static constructor does not take access modifiers or have parameters.

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

A static constructor cannot be called directly.

The user has no control on when the static constructor is executed in the program.

Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

Related Article
Using Static

Copy Constructors

Copy constructor takes the argument as an instance of a type. Copy constructor is used to create a new object by duplicating the state of an existing object, and done by copying the value of existing object.

When we copy object, it doesn’t copy but it actually creates object reference, that is why copy constructor become handy.

class Person
{
    // Copy constructor.
    public Person(Person previousPerson)
    {
        Name = previousPerson.Name;
        Age = previousPerson.Age;
    }

    //// Alternate copy constructor calls the instance constructor.
    //public Person(Person previousPerson)
    //    : this(previousPerson.Name, previousPerson.Age)
    //{
    //}

    // Instance constructor.
    public Person(string name, int age)
    {
        Name = name;
        Age = age;
    }

    public int Age { get; set; }

    public string Name { get; set; }
    
    public string Details()
    {
        return Name + " is " + Age.ToString();
    }
}

class TestPerson
{
    static void Main()
    {
        // Create a Person object by using the instance constructor.
        Person person1 = new Person("George", 40);

        // Create another Person object, copying person1.
        Person person2 = new Person(person1);

        // Change each person's age. 
        person1.Age = 39;
        person2.Age = 41;

        // Change person2's name.
        person2.Name = "Charles";

        // Show details to verify that the name and age fields are distinct.
        Console.WriteLine(person1.Details());
        Console.WriteLine(person2.Details());
    }
}
// Output: 
// George is 39
// Charles is 41

Instance constructor modifiers

  1. Access modifier – public, internal, private, protected
  2. Unmanaged code modifiers – unsafe, extern

Overloading constructors

Class and structs allow overload constructors. To avoid duplication one constructor may call another using this keyword.

using System;
public class Wine
{
public decimal Price;
public int Year;
public Wine (decimal price) { Price = price; }
public Wine (decimal price, int year) : this (price) { Year = year; }
}

When one constructor calls another, the called constructor executes first.
You can pass an expression into another constructor as follows:

public Wine (decimal price, DateTime year) : this (price, year.Year) { }

Implicit parameterless constructors

For classes, the C# compiler automatically generates a parameterless public constructor if and only if you do not define any constructors.

Constructor and field initialization order

Field initializations occur before the constructor is executed and in the declaration order of the fields.

Nonpublic constructors

  • Constructors do not need to be public
  • Common reason to have a nonpublic constructor is to control instance creation via a static method call.
  • The static method could be used to return an object from a pool rather than necessarily creating a new object, or return various subclasses based on input arguments.

Leave a Reply

Your email address will not be published. Required fields are marked *