Constructors and default, instance and static constructors in C#

Goud.Kv
Posted by in C# category on for Beginner level | Points: 250 | Views : 4132 red flag
Rating: 5 out of 5  
 1 vote(s)

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.
Recommendation
Read extern, in and async modifiers in C# before this article.

Introduction

So far, we have seen about extern, in and async modifiers in C#. Let's see about constructors with some examples in this chapter.

Objective

The main objective of this article is to learn about C# constructors with their types.

Constructor

Constructor is a specialized method which is used to create a usable block that is executable from the objects created by classes or structs.
  • Constructors will be declared with the same name of  class or struct. Example,
    class New
    {
        public New() // Constructor
        {
            .....;
        }
    }
  • They initialize the data members of the new object.
  • They create instances of classes or structs with runtime support.
  • Constructor without any parameters is known as default constructor.
  • These default constructors are called by the objects which are created by using new keyword.
  • Defining private constructors will prevent that class from being instantiated by any other outer members.
Example:
Let's have an example code which explains about the constructors clearly,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Man
{
    class Vehicle
    {
        string Name;
        public Vehicle(string Yamaha) // Constructor of class Vehicle
        {
            Name = Yamaha;
        }
    }

    class Program
    {
        static void Main()
        {
            Vehicle v1 = new Vehicle("R15"); // Calls the constructor
            Vehicle v2 = new Vehicle("Fz");  // Calls the constructor
        }
    }
}
In the above code, we have a constructor for a class vehicle. In the Main program, we are calling the constructor from the object created by using new keyword.

Types of constructors

Based on different operations, constructors are categorized into many types. They are,

Default constructor
We have already seen above that a constructor that have no parameters is called as a default constructor. C# compiler provides a default constructor to each and every class that we create. This is not shown in our C# code.

This default constructor is automatically removed by the compiler when you add a new explicit constructor.

default constructors doesn't have any parameters as well as any internal logic. 

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

namespace Man
{
    class Example
    {
        public int x, y;
        // Default parameter less constructor	
    }

    class Program
    {
        static void Main()
        {
            Example ex = new Example();
            ex.x = 5;
            Console.WriteLine(ex.x);
            ex.y = 0;
            Console.WriteLine(ex.y);
        }
    }
}
In the above code, we don't have any explicit constructor. But still the object is referring somewhere. That is to the default constructor created by C# compiler.

Now, run this above code and see the result,


Instance Constructor
These are the most commonly preferable constructors used to create instance members.

Public Constructors:
These are the instance constructors which are exposed to public and accessed by any other functions in our program.

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

namespace Man
{
    class MyClass
    {
        public int x;
        public MyClass(int i)
        {
            i = x;
        }
    }
    class Program
    {
        static void Main()
        {
            MyClass m = new MyClass(6);
            m.x = 4;
            Console.WriteLine(m.x);     // prints 4
        }
    }
}
The above code is an example of a simple instance constructor. Generally instance constructors are public which allows all methods to access it. This is not recommended in programming practice.

Output of the above code will be,


Private Constructor:
Private constructors are highly recommended instance constructors and mostly used for the classes that only has static members.
Private constructors doesn't allow any other classes to create instances of this class. That means we cannot call it externally.

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

namespace Man
{
    class MyClass
    {
        public int x;
        private MyClass(int i)
        {
            i = x;
        }
    }
    class Program
    {
        static void Main()
        {
            MyClass m = new MyClass(6); // This will throw compile time error
        }
    }
}
Observe the above code in which we are trying to create an object and calling it through private constructor.
This will gives a compile time error.

Static Constructor
These are used to initialize the static data that needs to be performed only once. Static constructor is called automatically after the creation of the first instance.

Static constructors are also called as type initializers. We cannot guarantee the execution time of static constructor and hence it is a lazy instantiation.

Static constructions can slow down the process of accessing to a class by the members and very hard to test.

Syntax,
class MyClass
{
    static int a;         // static variable.
    static MyClass(int i)
    {
        .......;          // only static members need to be initialized.
        ......;
    }
}

Conclusion

In this article, we tried to understand constructors and their types in C#. Hope you understand.

Thanks for reading.

Regards,
Krishna.

Recommendation
Read implicit, explicit and operator keywords in C# after this article.
Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)