Click here to Skip to main content
15,885,985 members
Articles / All Topics

Methods Part 1 – Constructors in C#

Rate me:
Please Sign up or sign in to vote.
4.82/5 (5 votes)
6 Sep 2015CPOL7 min read 9.3K   7  
Constructors in C# In this series of the articles I want to cover the different type of methods being present in the .NET framework.  The first type of the methods which I want to cover is the constructors in C#.

Constructors in C#

In this series of the articles I want to cover the different type of methods being present in the .NET framework.  The first type of the methods which I want to cover is the constructors in C#.  Yes constructors are also the methods whose names and return types have been reduced only to the name of the class.  Constructors in C# have been used to construct the values of data members as well member variables of the class.  In this article I will discuss all the important points related to constructors. Let’s start one by one.

 

Before starting the article you may want to read about reference type and value types here.

  1. As already mentioned constructors are the methods which allow instances of the type to be initialized and set the local data members to their initial or default values. Please have a look at the code example below
    public class MyClass
       {
           private int intVar = 5;
       }

     

    Now have a look at the IL code which I have generated using ILDasm.exe. Here we can clearly see that a constructor is created for the MyClass which loads the intVar’s value in Memory and calls the base class constructor after that. Also we can see that the constructor is defined as method.

    Class definition via IL

  2. It is always a point of confusion for some people that whether constructor is called first or memory is allocated first. It is important to note that to create the instances of the type, constructors are always called first to calculate the amount of memory required for instance’s data fields. Before calling the type’s constructor the memory space is judged for that type. After doing all these process the memory is allocated for the type in heap memory.
  3. Constructor as methods cannot be inherited.
  4. As constructors cannot be inherited that is why virtual, new , override, sealed or abstract key words are not allowed for constructors.
  5. If the user has not defined any constructor, in that case the compiler automatically defines default parameter less constructor as mentioned in the point 1, which calls the base class’s parameter less constructor. In this way the System.Object’s class constructor is the one which is called first.I have created the below code snippet to better understand about the constructors and the way they are initialized

     

    public class MyBaseClass
        {
            public int myLocalVar = 10;
    
            public MyBaseClass()
            {
                Console.WriteLine("Base Class myLocalVar Value: " + myLocalVar);
                myLocalVar = 20;
                Console.WriteLine("Base Class Constructor's myLocalVar Value: " + myLocalVar);
            }
        }
    
        public class MyDerivedClass : MyBaseClass
        {      
            public MyDerivedClass()
            {
                myLocalVar = 30;
                Console.WriteLine("Base class's myLocalVar value :" + myLocalVar);
                Console.Read();
            }
        }

    The above code shows the sequence in which constructors are initialized. If I create an instance of the derived class as shown below. This is also the scenario how the constructors behave in case of inheritance.

     

    MyDerivedClass derivedClass = new MyDerivedClass();

    The output of the above code will be as shown below ,

    Constructors output in C#

    As we can see from the output that the base class’s member variable is the one which is initialized in first place and after that the base class’s constructor is called and then the derived class’s constructor is called.

  6. If the class is abstract in that case the default constructor has protected accessibility otherwise the constructor has public accessibility.
  7. If there is no parameter less constructor in the base class in that case the compiler generated the compile time error as shown in the code below.Absence of parameter less constructor in base class in C#

    The error can be resolved by calling the base class constructor explicitly as shown below,

     

    public class MyDerivedClass : MyBaseClass
        {
            public MyDerivedClass(int localvar):base(localvar)
            {
    
            }
        }

     

  8. The same class constructors can be called using the this keyword. This scenario can be useful to initialize all the instance fields in a single constructor, if we have multiple constructors defined in a class. It is always advisable to initialize all the instance fields in a single parameter less constructor instead of initializing them at the same time when declaration(which is better known as inline instance field initialization). The code example is as following.

     

    public class MyClass
        {
            private int intVar;
            private string stringvar;
            private double doubleVar;      
    
    
            public MyClass()
            {
                intVar = 5;
                stringvar = "Hello";
                doubleVar = 3.14;
            }
    
            public MyClass(int x):this()
            {
    
            }
    
            public MyClass(string y):this()
            {
    
            }
        }

     

  9. Parameter less constructors are not allowed for value types in C# as we can see from the code below, compile time error is generated whenever we try to do itvalue type

    But we can definitely have constructors with parameters for value types and these constructors will be called only if we call them explicitly otherwise the value types are assigned with values of 0 or NULL.

    Code example for value type structure.

     

    public struct MyStruct
        {
            public MyStruct(int x)
            {
    
            }
        }

     

After talking about all the concepts about the constructors I want to discuss about the different type of constructors which we can create in C#.

  1. Static Constructors – As we know that instance constructors are used to initialize the data members of a class similarly the type(static) constructors are used to initialize the static data members and members variables of the type i.e. they are used to set the initial state of a type and not it’s instance.
    By default there are not type constructors defined within a type, and if we want to have a type constructor we cannot have more than one in a single type. Moreover type constructors don’t take parameters.
    Type(static) constructors for reference type and value types are defined below
    public class MyClass
        {
            static MyClass()
            {
    
            }
        }
    
    
        public struct MyStruct
        {
            static MyStruct()
            {
    
            }
        }

    As we can see from the above code snippet the type constructors does not have any access modifiers. These constructors are private by default to prevent from any developer-written code from calling them.

     

    If static constructors were public, this could have caused many subtle bugs in the code. First thing is that it is CLR which calls these static constructors while referring the first instance of the class.

    The calling of the type constructor is a tricky thing which I would like to discuss here. When the Just in Time (JIT) compiler is compiling a methods code, it sees what types are referenced in the code and if any of the types define a type(static) constructor. The compiler checks if the type’s static constructor has already been executed for this app domain. If the constructor has never been executed, the compiler call the static constructor and initializes all the static fields of the class. If the static constructor has already been called in that case compiler never executed it again.

    What If many threads want execute the same type constructor?

    In this type of scenario where multiple threads are executing the same method concurrently which refers our class with static constructor, the CLR ensures that the static constructor executes only once per AppDomain. To ensure this , when a static constructor is called, the calling thread acquires a mutually exclusive thread synchronization lock. So if multiple threads attempt to simultaneously call a type’s static constructor, only one thread will acquire the lock and other threads will be blocked. The first thread will execute the static constructor. After the first thread leaves the constructor, the waiting threads will wake up and will see that the constructor’s code has already been executed and they will not execute the code again.

    As an example to have a utilization of the static constructors, I would like to show a code snippet which is basically a data container class, which works on the data list. As a security that all the functions of this class which work on this data list need to have pre populated list. This can be achieved by having a static constructor in the class. Kindly have a look at the code below.

    public static class DataContainer
        {
            private static IList<int> list;
    
            static DataContainer()
            {
                list = new List<int>() { 1, 2, 3};
            }
    
            public static void AddItem(int intvar)
            {
                list.Add(intvar);
            }
    
            public static int RetrieveItemAt(int position)
            {
                if (list.Count > position)
                    return list[position];
                else
                    return -1;
            }
         }

    In the absence of the static constructor we must have used a method which should initialize and populate the list, in that case there are good chances of calling that function itself.

  2. Private Constructors

    Private constructors in C# are used in a class to prevent from creating an instance of the class from outside of the class.

    One of the scenario in which I want to use a private constructor is where I want all my initialization code to be present in only one constructor and not allowing that constructor to call from outside that class as shown in the code below.

     

    public class MyClass
        {
            private int intVar;
            private string stringvar;
            private double doubleVar;
    
    
            private MyClass()
            {
                intVar = 5;
                stringvar = "Hello";
                doubleVar = 3.14;
            }
    
            public MyClass(int x)
                : this()
            {
    
            }
    
            public MyClass(string y)
                : this()
            {
    
            }
         }

     

    Another case where we frequently use private constructors is singleton classes. These are the classes which maintain only a single instance of itself across whole of the application. Private constructors allow us to do it as shown in the code below .

     

    public class Singleton
        {
            private static Singleton _Singleton;
            private Singleton()
            {
    
            }
    
            public static Singleton GetInstance()
            {
                if (_Singleton == null)
                    _Singleton = new Singleton();
    
                return _Singleton;
            }
        }

     

That’s all which I want to discuss about the constructors. I hope this article has helped you to understand about the constructors and its concepts. Please let me know your thoughts about the article or if I have missed something to include in this article.

The post Methods Part 1 – Constructors in C# appeared first on Dot Net For All.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
I have 8 years of experience of mostly developing the .NET windows as well as web applications. Passionate about learning and sharing.

Visit my personal blog to know more about the .NET technology and increase your knowledge about C# and .NET. You can always follow me on twitter @dotnetforall.

Comments and Discussions

 
-- There are no messages in this forum --