Lesson 9

C# Constructors and Destructors with Programming Example


Objective

What are Constructors and Destructors in C#?
Static, private and instance constructors
Programming Example in C#

What are Constructors and Destructors in C#?

Constructor is a special method of class which never returns anything. It is used for initializing data member of class when instantiating object. Destructor is used for cleaning resources used by objects.

Define:

A Constructor can be defined in following manner:

public mobile()
{
}

public mobile(string color)
{
}

Guidelines

  1. Constructor must have same name of class.
  2. Each class has a default constructor with no parameters.
  3. It never returns value so never create constructors with return type data type.
  4. You can define more than one constructors in single class
  5. A constructor can be created with or without argument.

Programming Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Constructors
{
    class Example
    {
        //Constructors Created
        public Example()
        {
            Console.WriteLine("Hello, This is constructors Example");
        }
        public void HelloExample()
        {
            Console.WriteLine("Function Called");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Example ex = new Example();
            ex.HelloExample();
            Console.ReadKey();
        }
    }
}

Output

Hello, This is constructors Example
Function Called
__

Types of Constructors:

There are 3 types of constructors in C#.

  1. Instance
  2. Private
  3. Static

Instance Constructors

Instance Constructors are used to create and initialize instances. It is also considered as normal or default type constructors. It is invoked when you create new object of class. It can be declared as follow:

public Example(){}

Private Constructors:

A private constructor is created with private keyword. It is commonly used in class that contains static members only. However all the constructor is private by default if no modifier have used. The class which is no public constructors and have only private constructors cannot be initialized. It is useful to prevent creation of class when there is no method or fields.

Programming Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Private_Constructors
{
    class PvtCons
    {
        private PvtCons()
        {
        }
        public static string message;
        public static string showmessage()
        {
            return "Hello " + message;
        }

    }
    class Program
    {
        static void Main(string[] args)
        {
            //The following statement will raise error if you uncomment it. This is for demo to describe that private constructors can not be initialized.
            //PvtCons p = new PvtCons();
            PvtCons.message = "Jack";
            Console.WriteLine(PvtCons.showmessage());
            Console.ReadKey();
        }
    }
}

Output

Hello Jack
__

Static Constructors

Static Constructor is used to initialize static field or to perform a particular action that needs performed once only. It is called automatically when first instance is created or any static members are referenced. It is very useful in initializing static member of class.

Guidelines:

  1. A static constructor does not have parameters or access modifiers.
  2. It is called automatically and only once when initializes class.
  3. It cannot be called directly.
  4. You cannot control this constructor when it is executed in program.
  5. Normally this type of constructor is used when write entries in log file.

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace static_constructors
{
    class Temperature
    {
        static long temp;
        //This Static Constructor will initialize once
        static Temperature()
        {
            temp = 37;
        }
        public void showTemp()
        {
            Console.WriteLine("Temp is " + temp);
            temp += 5;
            
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Temperature t1 = new Temperature();
            t1.showTemp();
            Temperature t2 = new Temperature();
            t2.showTemp();
            Temperature t3 = new Temperature();
            t3.showTemp();
            Temperature t4 = new Temperature();
            t4.showTemp();
            Console.ReadKey();
        }
    }
}

Output

Temp is 37
Temp is 42
Temp is 47
Temp is 52
__

Explanation

In the above example there is a static variable and a static constructor. As mentioned above that static constructor initialized only once so the value of temp variable is set to 37. Now we have increased it value by 5. In the main method we have created 4 object of Temperature class but the noticeable thing is the temp variable not getting initialized after its first initialization. So at first initialization its value is set to 37 but its second initialization its value is 42 and in the third initialization its value reach up to 47.

You can see the difference easily if you change static keyword with public. Then you will see that the temp variable getting initialized at all time when object is created.

Destructors(~)

Destructor is also a special method of class which is initialized with tilde (~) symbol. It is used for releasing resources of unused or out of scope objects. However C# does not require much more memory management and it does it implicitly with garbage collection but if you have encapsulate unmanaged resources such as windows files or network connections you must use destructor for free up those resources.

Guidelines

  1. There can be only one destructor in a class.
  2. It cannot be inherited or overloaded.
  3. It cannot be called. It executes automatically.
  4. It doesn’t take modifier and parameters.

Declaration:

A destructor can be declared as follow:

~ MyClass() 
{
   // Cleaning up code goes here
}

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Destructor_Example
{
    class Dest
    {
        public void simplemessage()
        {
            Console.WriteLine("Hello");
        }
        ~Dest()
        {
            Console.WriteLine("Object Destructed");
            Console.ReadKey();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Dest d = new Dest();
            d.simplemessage();
            
        }
    }
}

Output

Hello
Object Destructed
__

Summary

In this chapter you have learned all about constructors and destructors in c#. Constructors are the special method which is used for initializing data members of class while initiating the object. Destructors are used for cleaning resources used by objects and free up system memories. In the next chapter you will learn about Encapsulation and Abstraction in c#.

BackNext