Topic : Constructor and Destructor in C#: Constructor | Destructor | Type Of Constructor



Constructor:

Constructor is a special method of a Class which will Invoke Automatically whenever Object of Class is created. Constructors are Responsible for Object Initialization and Memory Allocation of its class. If We create any Class Without Constructor, The Compiler will Automatically Create one Default Constructor for that class. The Default constructor Initializes all Numeric Fields in the class to Zero and All String and Object Fields to Null.



Declaring Constructor in The Class.

A Constructor has Exactly the same name as that of class and it does not have any return type. After Declaring The constructor we don't need to call it in main() method. Because constructor will automatically called, when an Object is being created. Let's have an Example here to know, how exactly we create an Constructor and how this constructor work.


/*Example: Constructor : InfoBrother:*/

using System;

namespace Constructor
{
    class Program  
    {
        public Program()  //constructor:
        {
            Console.WriteLine("Hi Method, You Didn't call be but still am here:");
        }


        void disp()  //method:
        {
            Console.WriteLine("Hi constructor, this Object called you Automatically:");
        }


        static void Main(string[] args)  //main() method:
        {
            Program pro = new Program();  //Creation of Object:
            pro.disp();   //method calling:
                    
            Console.ReadLine();
        }
    }
}


In Above example, did you see that we just define an Constructor. but we didn't call it in Our Main() Program. Its because, We create an Object, so Whenever we create an object of the class, the constructor called Automatically. if we define any constructor then the program will use that constructor else default constructor will work.



  • Type of Constructor:

    The Default Constructor does not have parameter or anythings. Its just Initializes all Numeric Variables in the class to Zero and All String and Object Fields to Null. But if we want Constructor to do something, then we can make Constructor in five Different Ways:
    » Default Constructor:
    » Parameterized Constructor:
    » Copy Constructor:
    » Static Constructor:
    » Private Constructor:



Default Constructor:

A constructor without having any parameters called default constructor. In this constructor every instance of the class will be initialized without any parameter values like as shown below.


/*Example: Default Constructor : InfoBrother:*/

using System;

namespace Default_Constructor
{
    class Program  
    {
        public int x, y;  //public Properties:

        public Program()  //constructor:
        {
            x = 10;
            y = 5;
        }


        static void Main(string[] args)  //main() method:
        {
            Program pro = new Program();  //Creation of Object:

            Console.WriteLine("Value of X is: " + pro.x);
            Console.WriteLine("Value of Y is: " + pro.y);

            Console.ReadLine();
        }
    }
}


Parameterized Constructor:

A constructor with at least one parameter is called as parameterized constructor. In parameterized constructor we can initialize each instance of the class to different values like as shown below.


/*Example: Parameterized Constructor : InfoBrother:*/

using System;

namespace Parameter_Constructor
{
    class Program  
    {
        public int x, y;  //public Properties:

        public Program(int a, int b)  //constructor with 2 Parameter:
        {
            x = a;
            y = b;
        }


        static void Main(string[] args)  //main() method:
        {
            Program pro = new Program(15,14);  //Creation of Object:

            Console.WriteLine("Value of X is: " + pro.x);
            Console.WriteLine("Value of Y is: " + pro.y);

            Console.ReadLine();
        }
    }
}


Copy Constructor:

A parameterized constructor that contains a parameter of same class type is called as copy constructor. Main purpose of copy constructor is to initialize new instance to the values of an existing instance. Check below example for this.


/*Example: Copy Constructor : InfoBrother:*/

using System;

namespace Copy_Constructor
{
    class Program  
    {
        public int x, y;  //public Properties:

        public Program(int a, int b)  //constructor with 2 Parameter:
        {
            x = a;
            y = b;
        }

        public Program(Program obj)  //copy Constructor:
        {
            x = obj.x;
            y = obj.y;
        }


        static void Main(string[] args)  //main() method:
        {
            Program pro = new Program(15,14);//Creation of Object:
            Program prog = new Program(pro); //pro detail copy to prog.

            Console.WriteLine("Value of X is: " + prog.x);
            Console.WriteLine("Value of Y is: " + prog.y);

            Console.ReadLine();
        }
    }
}


Static Constructor:

When we declared constructor as static it will be invoked only once for any number of Object of the class and it’s during the creation of first Object of the class or the first reference to a static member in the class. Static constructor is used to initialize static fields of the class and to write the code that needs to be executed only once.


/*Example: Static Constructor : InfoBrother:*/

using System;

namespace Static_Constructor
{
    class Program  
    {
        public string x, y;  //public Properties:

        static Program()  //static Constructor:
        {
            Console.WriteLine("Static Constructor: ");
        }

        public Program()  //Object Constructor:
        {
            x = "Object";
            y = "Constructor.";
        }


        static void Main(string[] args)  //main() method:
        {
            /*both Static and object constructor will invoked here
              for the first Object: */
            Program pro = new Program();
            Console.WriteLine(pro.x + " " + pro.y);

            /*Only object Constructor will invoked here.
            for the second Object. */
            Program prog = new Program();
            Console.WriteLine(prog.x + " " + prog.y);

            Console.ReadLine();
        }
    }
}

  • More About Static Constructor:

    » Static constructor will not accept any parameters because it is automatically called by CLR.
    » Static constructor will not have any access modifiers.
    » Static constructor will execute automatically whenever we create first Object of class.
    » Only one static constructor will allowed in the class.



Private Constructor:

Private constructor is a special instance constructor used in a class that contains static member only. If a class has one or more private constructor and no public constructor then other classes is not allowed to create Object of this class this mean we can neither create the object of the class nor it can be inherit by other class. The main purpose of creating private constructor is used to restrict the class from being instantiated when it contains every member as static.


/*Example: Private Constructor : InfoBrother:*/

using System;

namespace Private_Constructor
{
    class construct   //another Class:
    {
        public string str;
        public construct(string s) //public constructor:
        {
            str = s;
        }

        private construct()  //Private constructor:
        {
            Console.WriteLine("Private Constructor: ");
        }
    }


    class Program    //main class:
    {
        static void Main(string[] args)  //main() method:
        {
            //we can't create the object for private constructor:
            //it's the object for public constructor with parameters.
            construct cons = new construct("Hello every one: ");

            /* Compiler will not allow us to create object without parameters 
             like this: construct cons = new construct(); */

            Console.WriteLine(cons.str);
            Console.ReadLine();
        }
    }
}

In Above Example, We can create the object of class with parameters. but compiler will not allow us to create the object without parameters.



  • More About Private Constructor:

    » One use of private construct is when we have only static member.
    » Once we provide a constructor that is either private or public or any, the compiler will not allow us to add public constructor without parameters to the class.
    » If we want to create object of class even if we have private constructors then we need to have public constructor along with private constructor.



Destructor:

A Destructor is a Special member method of a Class that call automatically each time when an object is Destroyed. An Object is Destroyed when it Goes out of Scope. A Destructor has Exactly the Same name as that of the Class with a prefixed tilde (~) and it can neither return a Value nor can it take any parameters. We use destructors to Only releasing memory resources before exiting the Program.



Programmers usually do Not need to Perform as many tasks in Destructor as they do in constructor. We Need constructor to just release the Memory before exiting the Program.



The programmer has no control on when the destructor is going to be executed because this is determined by the Garbage Collector. The garbage collector checks for objects that are no longer being used by the application. It considers these objects eligible for destruction and reclaims their memory. Destructors are also called when the program exits. Now let's have an example, where we will see how this destructor work.



/*Example: Destructor : InfoBrother:*/

using System;

namespace Destructor
{
    class House
    {
        private int SquareFeet;
        public House()  //Constructor:
        {
            Console.WriteLine("House Created Successfully: ");
        }

        public int getLength(int L)  //Method:
        {
            SquareFeet = L;
            return SquareFeet;
        }


        ~House()  //Destructor:
        {
            Console.WriteLine("Oops ! House Destroyed: ");
        } 
    }

    class Program    //our Main class:
    {
        static void Main(string[] args)  
        {
            House build = new House();  //Object Creation:
            Console.WriteLine("Square Feet = " +build.getLength(1000));

            Console.ReadKey();
        }
    }
}


  • More About Destructor:

    » Destructors are invoked automatically, and cannot be invoked explicitly.
    » Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.
    » Destructors are not inherited. Thus, a class has no Destructors other than the one, which may be declared in it.
    » Destructors cannot be used with structs. They are only used with classes.
    » An instance becomes eligible for destruction when it is no longer possible for any code to use the instance.
    » Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.
    » A destructor does not take modifiers or have parameters.



  • Read more...

    Every C# Class Object Invoked automatically 4 Methods:
    » A Default Constructor:
    » A Default Destructor:
    » A Copy Constructor: The Copy constructor executes when we pass an object as an argument to a method, Making a local copy within the class.
    » A Default Assignment Operator: This operator allows us to assign one object to another.



















I Tried my Best to Provide you complete Information regarding this topic in very easy and conceptual way. but still if you have any Problem to understand this topic, or do you have any Questions, Feel Free to Ask Question. i'll do my best to Provide you what you need.

Sardar Omar.
InfoBrother





WRITE FOR INFOBROTHER

Advertising






Advertisement