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

Using of global variables in C# - Drawbacks & Solutions

How using global variables can have implications on the design, maintainability, and test-ability of C# code: Harder to understand and reason about the code:       class Program     {         public static int globalCounter = 0;         static void Main()         {             globalCounter++;             Console.WriteLine(globalCounter);         }     }   In this example, the global variable globalCounter is accessible from anywhere in the program, including the Main method. It's not clear where the value of the globalCounter is updated, it could be updated in other methods or classes, making it harder to trace the flow of data and understand the source of bugs.   More prone to errors:       class Program     {         public static string globalString;         static void Main()         {             globalString = "Hello" ;             Method1();             Method2();         }         static void Method1()         {

Task Parallel Library (TPL) and Akka.NET Alternatives

Task Parallel Library (TPL) and Akka.NET are among the most commonly used libraries for parallel and concurrent programming in the .NET ecosystem. However, there are also several other options available, depending on your specific needs: Parallel Language Integrated Query (PLINQ) is a parallel programming feature of .NET that provides an easy and efficient way to perform operations on collections in parallel. LINQ (Language Integrated Query) is a powerful feature in .NET that allows developers to work with data in a more declarative and language-integrated manner. While LINQ queries are inherently sequential, PLINQ extends LINQ by providing parallel versions of the query operators, allowing some queries to execute faster by utilizing multiple processors or cores on a machine. PLINQ is great when you are working with large collections where operations might be CPU-intensive or I/O-bound and could potentially be sped up by parallel execution. Here is a simple example of a PLI

SOLID Principles with Real World examples in C#

  SOLID Principles with Real World examples in C#   SOLID principles are formed by using S Single Responsibility Principles (SRP) O Open Closed Principle (OCP) L Liskov’s Substitution Principle (LCP) I Interface Segregation Principle (ISP) D Dependency Inversion Principle (DIP)   S Single Responsibility Principles (SRP) There should never be more than one reason for a class to change, to be precise one class should have only one responsibility Single Responsibility Principles (SRP) Real world example, A perfect match for SRP is Microservices , a Microservice will not contain functionalities other than the one it is designated to do,  Example ·                   Order Processing Service, ·                   Shipment Management Service, ·                   User Authentication Service, ·                   Catalogue List Service       class OrderProcessor     {         public void Process(Order order)         {             // Check inven