SIGN UP MEMBER LOGIN:    
ARTICLE

Constructors and Destructors in C#.Net

Posted by ramakrishna basagalla Articles | C# Language December 09, 2010
Constructors are special methods called when a class is instantiated.
Reader Level:



Constructor

Constructors are special methods called when a class is instantiated.

  • Constructor will not return anything.
  • Constructor name is same as class name.
  • By default C# will create default constructor internally.
  • Constructor with no arguments and no body is called default constructor.
  • Constructor with arguments is called parameterized constructor.
  • Constructor by default public.
  • We can create private constructors.
  • A method with same name as class name is called constructor there is no separate keyword.

Sample Program:

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

namespace BRK.ConstructorExample
{
    class Welcome
    {
        // Default constructor
        public Welcome()
        {
            Console.WriteLine("Welcome message from Default Constructor...");
        }

        // Parametarized constructor
        public Welcome(string name)
        {
            Console.WriteLine("\n\nThis message from parametarized constructor");
            Console.WriteLine("Welcome to Constructor sample, by {0}", name);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // Creating object for Welcome class
            // This will called default constructor
            Welcome obj = new Welcome();

            // Creating object for welcome class by passing parameter
            // This will called parametarized constructor which matches
            Welcome pObj = new Welcome("Ramakrishna Basgalla");

            Console.Read();
        }
    }
}

Output:

const1.gif

Private Constructor

As I mentioned above we can create private constructors, but we have limitation in using that. The following program shows how to create and use a private constructor.

Sample Program:

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

namespace BRK.PrivateConstructorSample
{
    class Welcome
    {
        // Default private constructor
        private Welcome()
        {
            Console.WriteLine("Welcome message from Default Private Constructor...");
            Console.WriteLine("Created by Ramakrishna Basagalla (-:");
        }

        static void Main(string[] args)
        {
            // Creating object for Welcome class
            // This will called default private constructor
            Welcome obj = new Welcome();

            Console.Read();
        }
    }
}

Output:

const2.gif

To use a private constructor we should have main function in the same class, generally we will define constructors in different classes so defining private constructors is not that much useful.

Static Constructor

A static constructor has the same name as the class name but preceded with the static keyword; it will be called at the time of class load.

  • No access specifier for static constructor.

  • Static constructor will not return anything.

  • Static constructor will accept only static members.

  • Static constructor will call at the time of class loading.

  • Static constructor will not allow overloading, so there is no parameterized static constructor.

Sample Program:

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

namespace BRK.ConstructorExample
{
    class Welcome
    {
        public static string Name = "Ramakrishna Basagalla";

        // Static Constructor
        static Welcome()
        {
            Console.WriteLine("Welcome message from static Constructor...");
            Console.WriteLine("{0} name is coming from static member",Name);
        }

        // Parametarized constructor
        public Welcome(string name)
        {
            Console.WriteLine("\n\nThis message from parametarized constructor");
            Console.WriteLine("Welcome to Constructor sample, by {0}", name);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // Creating object for welcome class by passing parameter
            // This will called parametarized constructor which matches
            Welcome pObj = new Welcome("Ramakrishna Basgalla");

            Console.Read();
        }
    }
}


Output:

const3.gif

In the above program we have created parameterized object for Welcome class, here the static constructor is called at the time of class load after then it's called corresponding parameterized constructor.

Destructors

.Net will clean up the un-used objects by using garbage collection process. It internally uses the destruction method to clean up the un-used objects. Some times the programmer needs to do manual cleanup.

Syntax:

~<ClassName>
{}

Sample Program:

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

namespace BRK.ConstructorExample
{
    class Welcome
    {
        // Default constructor
        public Welcome()
        {
            Console.WriteLine("Welcome message from Default Constructor...");
        }

        // Destructor
        ~Welcome()
        {
            Console.WriteLine("Destructor called");       
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // Creating object for Welcome class
            // This will called default constructor
            Welcome obj = new Welcome();

            Console.Read();
        }
    }
}

Note: Destructor will call after execution of the program.

Let me know if you need any other technical articles in .Net.

HAPPY CODING.

Login to add your contents and source code to this article
Article Extensions
Contents added by Vijay Gill on Dec 10, 2010
Something is wrong with the commenting functionality of this site. My line-breaks are not working. All text appears as one paragraph! So I am adding my comments as extension.


Hi Ramakrishna,

Please do not take this a harsh criticism, but see my points below

Constructor by default public. -> Wrong. It is not. I am sure you did not even try checking it :)
Static constructor being called at the time of class load? Not well explained. See link http://msdn.microsoft.com/en-us/library/k9x6w0hc%28VS.80%29.aspx

Also your explanation about private constructors and Main method is not correct.
The reason you could instantiate your class in Main method because Main method had access to the private constructor.

Any method in a class has access to the private constructor of that class. More details: http://msdn.microsoft.com/en-us/library/kcfb85a6%28v=vs.80%29.aspx

Also private constructors are not useless. Try googling for Factory Pattern.

Destructor will call after execution of the program. -> not 100% correct. See http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx

Good luck for next article.
Vijay

Code to check if constructor is public / private / whatever by default

    class Program
    {
        static void Main(string[] args)
        {
            var test = new Test();
            test.F();
        }
    }

    public class Test
    {
        Test()
        {
            Console.WriteLine("Constructor");
        }

        public void F()
        {
            Console.WriteLine("Method F()");
        }
    }
share this article :
post comment
 

@Sam: I hope this does not start a flamewar which I never intend to. But developing good coding habits right from the beginning is very important. In C# IDisposable is a pattern that C# developers use in the same way as C++ developers use destructors. It is used in .Net framework itself for a lot of classes. IDisposable pattern, though a bit complex, is not rocket science and beginners can always start with the simplest approach and improve their knowledge+code as they go on. The main benefit of IDisposble is 'deterministic nature' of its usage.

Posted by Vijay Gill Jan 22, 2012

Vijay and others, the important thing is that the subjects of destructors and IDisposable is complex. The important thing is that most managed code does not need any of it. Saying that we need IDisposable instead of destructors makes things more confusing. Can someone please make it clear that a beginner can ignore this stuff until they learn more? A C# beginner that is experienced with C++ can get really confused about this stuff and usually they don't need it.

Posted by Sam Hobbs Jan 21, 2012

@Sam: relying on destructors to clean up unmanaged resources is not a good idea because calling of destructors is dependent on GC (http://msdn.microsoft.com/en-us/library/66x5fx1b.aspx). Better way to deal with that is implementation of IDisposable interface (which when used with 'using' statement) for releasing unmanaged resources deterministic way. Vijay

Posted by Vijay Gill Jan 21, 2012

Destructors are usually not needed, correct? I think the first thing that should be said about Destructors is that they are usually not needed. The most common use of destructors is to do cleanup of unmanaged objects.

Posted by Sam Hobbs Jan 20, 2012

Very useful for beginner student.......

Posted by Vineet Kumar Saini Nov 26, 2011
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Nevron Gauge for SharePoint
Become a Sponsor