Skip to main content

Static Constructors in C # (C Sharp)


If you want your class to be initialize the Static members and if you want anything to be executed only once then you can use the static constructor,

For example:  Creating a Log file, Inform the user that the class has been called,

Here is the MSDN Explanation, we will look it case by case

1) Why Static constructor actions will be performed only once regardless of times the object is created?

CLR is locking the thread and making sure that only one thread is running per App Domain for specific set of purposes like writing log entries, holding session values, implementing Singletons…

See the example program 

 class ClassA
  {
   static ClassA()
        {
            Console.WriteLine("Static Constructor ClassA is called!");
        }
        public ClassA(int Count)
        {
            Console.WriteLine("Public Constructor ClassA is called! Count is :" + Count.ToString());
        }
    }
class Program
{
        static void Main(string[] args)
        {
            ClassA ClsObjA = new ClassA(2);
            ClassA ClsObjB = new ClassA(3);
            Console.ReadLine();
        }
     }

Output:

Static Constructor ClassA is called!
Public Constructor ClassA is called! Count is :2
Public Constructor ClassA is called! Count is :3

Further Reading for Static constructor deadlocks is available here

2) Static Constructors are Parameter Less

class ClassA
    {
        static ClassA(int A)
        {

        }
    }
Compile Time Error: 
‘ClassA.ClassA(int)': a static constructor must be parameter less
Why static constructor in c# not allowing parameters? Here you can find the details from StackOverflow

The simple answer is the static constructor will be executed way before the object’s initialization before the first instance is created so there is no way to pass the parameters to the constructor.

3) Static Constructors are not allowing access modifiers
So what is the access type of the Static Constructor? and why this is implemented in this way?

Let’s start with default access modifier for any constructor, that is private, so what private does in terms of constructing? It will definitely stop the instantiate process, so this will not be a private, if not then what it might be have the chances to be public (Please someone clarify this, most of the sites say this is private, but I don’t see a reason in it)

4) Static Constructor is automatically called before the first instance is created

This we have seen in previous example 

5) Static Constructor cannot be called directly

Yes, it's the design, so we don't need to call it explicitly, it will get called implicitly.

Comments

Popular posts from this blog

Task Parallel Library (TPL) and Akka.NET: Differences

Task Parallel Library (TPL) and Akka.NET are both powerful tools in the .NET ecosystem for handling parallelism and concurrency, but they serve different purposes and use different models of computation. Here are some key differences:s 1.    Actor Model vs Task-Based Model: Akka.NET is built around the actor model, where actors are the fundamental units of computation and they communicate by exchanging messages. TPL, on the other hand, is task-based. It's designed to make developers more productive by simplifying the process of adding parallelism and concurrency to applications. TPL uses tasks (which are independently executing work units) and provides various ways to control and coordinate them. 2.    Fault Tolerance: One of the key features of Akka.NET is its built-in fault tolerance. It has a "let-it-crash" philosophy, where the system is designed to self-heal from errors. If an actor fails, its parent actor can decide on the supervision strategy: either to resta

Extension Methods - Advanced

Here we will see how can we use the Extension Methods in advanced manner in other types Imagine you often need to retrieve items from a List based on a custom criterion that the built-in LINQ methods don't cover. Extension Methods for Lists: Filtering based on Custom Criteria And the output would be   Extending Enums: Displaying Descriptive Strings Output: Extending DateTime: Calculating Age     Output: The code samples can be found at https://github.com/oneananda/C_Sharp_Examples/tree/main/ExtensionMethods