Private and Static Constructors in C# Simplified

In this article, we discuss in detail about the concepts of Private and Static constructors in C# programming language and how they are useful.

Constructor is a common concept of any Object Oriented High Level Programming language. It is core to the classes and objects; the strange method like syntax with no return type and the first block to be called within a class when an object of its type is created.

Although Constructors are marked as public by default for its visibility level, C# also supports two special kinds of Constructors – Private Constructor and Static Constructor. These two are used for different purposes and are employed under special scenarios.

In this article, let’s look in brief at what a Private Constructor and a Static Constructor does and how they’re useful.

What is a Private Constructor?

  • Private Constructor is a special instance Constructor, used in classes that contain static members only.
  • If a class has one or more private Constructors and no public Constructor, other classes can’t create instance of this class.
  • In general, when there are no constructors declared in a class, the compiler adds a default parameterless public Constructor. Declaration of an empty private Constructor prevents the automatic generation of parameterless Constructor. This makes the class virtually having no public constructors and one private Constructor.
  • For example, the Math class from the default namespace contains all static methods (Floor, Round, Pow etc.) which don’t need an instance to be called. In this case, there’s no use in creating an instance of Math class and it only adds to memory load. Hence we might want to prevent unnecessary initialization of such classes.
  • In such cases although using a private constructor helps, a static class might be of better design than a private constructor.
  • Private constructors are also core to the implementation of a Singleton design pattern.

Example –

public class SomeClass 
{
    // private constructor
    // prevents default public constructor
    private SomeClass() 
    {
        // some context here
    }

    public void SomeMethod() 
    {
        // some context here
    }
}


#caller method:#
var someClass = new SomeClass();
// compilation error occurs at this line

What is a Static Constructor?

  • Static constructors are used to initialize static members of the class or to perform particular actions that need to be performed only once. A normal constructor is called each time an instance of the class is created. But in some cases, we might want the initialization of some members to happen only once in the entire application life.
  • Static constructor is automatically called before the first instance of the class is created or any static member of the class is referred.
  • A Static constructor can’t have any access modifiers or parameters.
  • A Class or struct can have only one static constructor.
  • A Static constructor can’t be inherited or overloaded. You can only have one single static constructor for a class.
  • User can never know when the static constructor is called. Nor the user has any control over its call. Its called over by the CLR / Runtime over a period of time during the application execution when some criteria are met (such as the ones mentioned before) and calls implicitly.
  • A static constructor doesn’t have any access modifier (public, protected..) nor is allowed.

Example –

public class SomeClass 
{
    private static HttpClient _client;
    
    static SomeClass() 
    {
        _client = new HttpClient();
    }

    public void SomeMethod() 
    {
        // some context here
    }
}

Static Constructors and Inheritance

  • Although static constructors don’t have inheritance, their order of execution in an inherited setup is interesting.
  • In general, when we create instance of a derived class, it internally calls the top most base class constructor and the call starts from there.
  • But when the derived class contains a static constructor, it is called first; even before the base class constructor is called.
  • If the base class also contains a static constructor, the derived class static constructor is followed by the base class static constructor and then the call goes to the base class constructor.

Example –

namespace DumpConsoleApp
{
    public class SomeBaseClass
    {
        static SomeBaseClass()
        {
            Console.WriteLine(
                "This is SomeBaseClass static constructor");
        }

        public SomeBaseClass()
        {
            Console.WriteLine(
                "This is SomeBaseClass constructor");
        }
    }

    public class SomeDerivedClass : SomeBaseClass
    {
        static SomeDerivedClass()
        {
            Console.WriteLine(
                "This is SomeDerivedClass static constructor");
        }

        public SomeDerivedClass()
        {
            Console.WriteLine(
                "This is SomeDerivedClass constructor");
        }
    }
}


#caller method#
SomeBaseClass b = new SomeDerivedClass();

#output:#
This is SomeDerivedClass static constructor
This is SomeBaseClass static constructor
This is SomeBaseClass constructor
This is SomeDerivedClass constructor

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Conclusion

In this article, we have discussed in detail about the concepts of Private and Static constructors in C# programming language. These structures are core to the Object Oriented Programming paradigm and have their own set of unique properties, which make them useful for certain scenarios; also used in making Singletons.


Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *