Constructors and Destructors are the very small chapter in C# and can be learned easily. It is easy to understand concept of constructors and destructors.

What are Constructors and Destructors in C#?

Constructors: Constructors are the special method of class which is used when create object. It like  to method but it has same name as class. It is created with the same name of class and notable thing is that it never returns value so you can’t use this method for returning some value.

Guidelines while creating Constructors:

  • It should be the same name of class.
  • It never returns value so don’t create constructors with return type.
  • A class may have several constructors
  • A constructors may initialize with our without argument.

Example

class Hello
{
    //Constructors
    public Hello()
    {
    }
    //Parameterized Constructor
    public Hello(int num)
    {

    }
    public Hello(string msg)
    {

    }
}
Destructors (~): Destructors are used to removing all the object of classes and releasing resources. It is works like a garbage collector. It is useful to use destructor for security reasons as it clears memory by removing all the object of  classes.

Guidelines while creating Destructors:

  • Destructor is used followed by tilde (~) Symbol
  • It is only used with class not the structs
  • A class can only have one destructor
  • It is cannot be overloaded or inherited.
  • It cannot be called. It is invoked automatically.
  • It does not have parameters.

Example

class Hello
{
    ~Hello()  // destructor
    {
        // cleanup statements...
    }
}

Leave a Reply

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