Search Forum
(53671 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


 
Printable Version

An Intro to Constructors in C#
By Neeraj Saluja

Introduction

Constructors are very useful but only and only if we are aware of the best way to use it for a requirement. One need to be sure of the input that has be given to the constructor and the way the class is supposed to be used. Some of the vast variety of design pattern suggests the usage of Constructors in smart way. A Contructor can thus play a vital role in defining the behavior of the class. Let us have a detailed look at couple of scenarios how the usage of Constructors in smart way can be helpful.

Singleton Pattern

Singleton Pattern is one of the most talked about design pattern. It says that a given class can have at the most one instance at any given moment of time. Such a class which ensure that it has only one instance is called Singleton class. Well, it does not limit the simultaneous use of the single instance - more than one handle ( reference) to the same instance of the singleton class can persist simultaneouly. 

Let us see how this can be achieved by using constuctors effectively.

public class Singleton {
private
static Singleton instance; private
string m_city; //

Note the private constructor. You can not directly create the instance of this class
private Singleton()
{
}

public string City
{
get {return m_city;}
}

public static Singleton GetSingletonObject()
{
// Use 'Lazy initialization' 
if (instance == null)
{
instance = new Singleton();
}
return instance;
}

public void ChangeCityName(string newCityName)
{
m_city = newCityName;
}
}

The object of the above class cannot be created directly as it has got just private constructor. But still this class Singleton can be used effectively with the help of the static method - GetSingletonObject. In the class we hold the reference of its own object in the variable "instance". In the GetSingletonObject method we first deternmine whether the instance of the class has been previously created and exist or not. If not we create the instance using the code "instance = new Singleton();" and return that instance object to the caller. The caller gets the reference to the only object ( Singleton ). When another request to GetSingletonObject  comes up, it returns the already instantiated instance.

Let us see how it works

// Getting the Singleton instance of the class
Singleton obj1 = Singleton.GetSingletonObject();

// Changing the property using the public method.
obj1.ChangeCityName("Bangalore"); 

// Getting the handle of the same instance at another place
Singleton obj2 = Singleton.GetSingletonObject(); 

// Using the public property
Console.WriteLine(obj2.City); 

It returns "Bangalore" on the Console Output Screen.

Key Notes for such implementation : 

  • Use private or protected constructor to ensure that the object of the class cannot be instantiated directly.
  • Though you have not created the instance of the class, you can still access the public methods of the class with the instance which was created internally.
  • Note that you do not have any public no-parameter (default) constructor but still "instance = new Singleton();" works perfectly fine. Copy Constructor

    C# does not provide the copy constructor by default. So if you want to have the identical copy of the object having the same values for properties and member variables as the existing object,  then you need to write the method by yourself. Either you can do it by writing a seperate method Or you can do that by a Copy Constructor. 

    Let us see how it works

    public class Employee
    {
    public string name;
    public string city;
    
    public Employee()
    {
    }
    
    // Copy constructor.
    public Employee(Employee emp)
    {
    name = emp.name;
    city = emp.city;
    }
    
    // Instance constructor.
    public Employee(string name, string city)
    {
    this.name = name;
    this.city = city;
    }
    
    // Get Details
    public string Details
    {
    get
    {
    return name + " is from " + city.ToString();
    }
    }
    }
    
    

    Note the copy constructor of Employee above. It takes instance of the Employee class as an input and after creating the new instance copies the values of the member variable (of emp1)  to the member variable of new instance (emp2) of Employee.

    Employee emp1 = new Employee("Harry","Austin,TX");
    Employee emp2 = new Employee(emp1);
    emp2.name = "Tony";
    
    Console.WriteLine(emp1.Details);
    Console.WriteLine(emp2.Details);

    The output of the above code would be

    Harry is from Austin,TX
    Tony is from Austin,TX

    Key Notes for such implementation : 

  • Copy works on value and not reference Conclusion :  

    Constructors can play a vital role in class design and implementation, if used appropriately. There are quite a few design patterns like Singleton Pattern which can be achieved by using the Constructors effectively. Constructors are one of the basic feature of any language and available to us to get exploited, the challenge lies in determining the suitable design to cater the business requirement. This article is focused on implementing Constructors to address requirements, to have a overview of Constructors please go through the article An Intro to Constructors in C# 

    References :  

    For Singleton Pattern : dofactory.com


    In case of any queries/issues/concerns, feel free to post them or mail me at neeraj_saluja@gmail.com.

    Happy Reading... Enjoy... Thanks