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?
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