Jitesh Byahut 4/18/2014 3136

Constructor In C#

Constructor is a special type of function that name is same as class name. Object crated time constructed must be fired, means when constructor is fired then, object is created, that's why it is called constructor. It has no return type. Constructor can be overloaded. Constructor used to initialize the member variable of class. Constructor should be declare in public section.

Now we are consider one by one constructor features:

Constructor is a special type of function that name is same as class name.

    class Test

    {   

        // Constructor

        public Test()

        {            

        }

    }

It has no return type.

If you forcing to put return type then it converted into a method and it will throw an exception because method name inside a class is not same as class name.

    class Test

    {   

        // It will throw an exception

        public void Test()

        {            

        }

        // 'Test': member names cannot be the same as their enclosing type

    }

Object created time constructor must be fired.

    class Test

    {     

        // Constructor

        public Test()

        {          

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            // Object creation time constructor fired

            Test test1 = new Test();

        }

    }

Constructor can be overloaded

    class Test

    {     

       

        // Constructor

        public Test()

        {           

            Console.WriteLine("Default Constructor");

        }

        // Constructor

        public Test(string name)

        {

            Console.WriteLine("name: " + name);

        }

        // Constructor

        public Test(String name, string email)

        {

            Console.WriteLine("name: " + name + ", email: " + email);

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

           

            Test test1 = new Test();

            Test test2 = new Test("asphelps");

            Test test3 = new Test("asphelps", "contact@asphelps.com");

 

            Console.Read();

        }

    }

 

    // Optput

    // Default Constructor

    // name: asphelps

    // name: asphelps, email: contact@asphelps.com

Types of constructor


1. Default constructor

2. Static constructor

3. Private constructor

4. Parameterized constructor

Default constructor

A constructor that takes no parameter is known as Default constructor. Default constructor fired always whenever an object is creating using new keyword. It doesn't accept any parameter or arguments.

namespace ConstructorTest

{

    class Test

    {

        // Define Default Constructor

        public Test()

        {

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            // Default constructor automatically fired at object creation time

            Test test = new Test();

        }

    }

}

If you don't provide a constructor in your class, then system automatically generate a Default constructor that will fire at time of object creation using new keyword.

    class Test

    {

        // No Default Constructor Define       

    }

    class Program

    {

        static void Main(string[] args)

        {

            // System automatically generate a Default constructor

            Test test = new Test();

        }

    }

Parameterized Constructor

A constructor that accept parameter is known as Parameterized constructor.

    class Test

    {

        public string Name { get; set; }

        public string Email { get; set; }

        // Parametrized Constructor

        public Test(string name, string email)

        {

            Name = name;

            Email = email;

        }

 

        public void ShowDetails()

        {

            Console.WriteLine("Name : " + Name);

            Console.WriteLine("Email : " + Email);

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            // Calling Parametrized Constructor

            Test test1 = new Test("Jitesh Kumar", "jitesh@asphelps.com");

            test1.ShowDetails();

           

            Console.Read();

        }

    }

 

    // Output

    // Name : Jitesh Kumar

    // Email : jitesh@asphelps.com

Private constructor

A constructor which has private access modifier is known as Private constructor. Main purpose of private constructor to prevent the creation of object from outside of class. You can define private constructor in your class when all members inside class are only static and you don't want to create the object of that class. Using private constructor neither you create a object of that class nor it can inherit by other class. If you want to create object of class that contain private constructor then you need to write a public constructor along with private constructor.

Private constructor is used to create singleton class. Singleton class has only one object is created outside the class. In singleton class more than one object is created inside the class.

    class Test

    {

        // Define Private Constructor

        private Test()

        {

        }

 

        static string Msg;

        public static void ShowMessage()

        {

            Console.WriteLine(Msg);

        }

 

    }

    class Program

    {

        static void Main(string[] args)

        {

            // If you try to create object then it will throw exception

            Test test = new Test();

            //'ConstructorTest.Test.Test()' is inaccessible due to its protection level

        }

    } 

Access member of private conctructor class.

    class Test

    {

        // Define Private Constructor

        private Test()

        {

        }

 

        public static string Msg;

        public static void ShowMessage()

        {

            Console.WriteLine(Msg);

        }

 

    }

    class Program

    {

        static void Main(string[] args)

        {

            // Access all member by class name only

            Test.Msg = "Hello Asphelps";

            Test.ShowMessage();           

        }

    }

 

    // Output

    // Hello Asphelps

Static Constructor

Static constructor used to initialize static data of class. Static constructor cannot take parameter. Static constructor cannot have access modifier. There are only one static constructor in the class. It will fired automatically at the first object of class is created, after that it will not be fired.

    class Test

    {       

        // Static Constructor

        static Test()

        {          

            Console.WriteLine("Static Constructor");           

        }

 

        // Default Constructor

        public Test()

        {           

            Console.WriteLine("Default Constructor");

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            // First time static and default constructor called

            Test test1 = new Test();

 

            // Optput

            // Static Constructor

            // Default Constructor

 

 

            // Second time only default constructor called

            Test test2 = new Test();

            // Output

            // Default Constructor

           

           

            Console.Read();

        }

    }

If you concentrate on individual output, then you can understand the features of static constructor.

Copy Constructor

Copy Constructor is used to copy the data of one object into newly created object. In copy constructor we pass parameter i.e. object of that class type.

    class Test

    {

        public string Name { get; set; }

        public string Email { get; set; }

        // Default Constructor

        public Test()

        {           

        }

        // Copy Constructor

        public Test(Test objTest)

        {

            Name = objTest.Name;

            Email = objTest.Email;

        }

 

        public void ShowDetails()

        {

            Console.WriteLine("Name : " + Name);

            Console.WriteLine("Email : " + Email);

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            // Calling Default Constructor

            Test test1 = new Test();

            test1.Name = "Jitesh Kumar";

            test1.Email = "jitesh@asphelps.com";

            test1.ShowDetails();

 

            // Calling Copy Constructor

            Test test2 = new Test(test1);

            test2.ShowDetails();

 

            Console.Read();

 

        }

    }

 

    // Output

    // Called test1

    // Name : Jitesh Kumar

    // Email : jitesh@asphelps.com

 

    // Called test2

    // Name : Jitesh Kumar

    // Email : jitesh@asphelps.com


Please give your feedback for improving this page