i want to know why class contains single static constructor only?
Because it's being called automatically and there is no way to pass any parameter to that constructor. That's why only one, parameterless static constructor is possible.
what is the real time scenario for static constructor ?
You should use it for any work that has to be done before class is used and that has to be done only once.
how it differs from private constructor?
Private constructor is being run when you want it to run. Static constructor is run by CLR before class
is used for the first time and you can determine when it happens.
And real-code example of static constructor usage - it creates an Expression Tree and compiles it to be used later and safe Expression Tree compilation from executing every time TestFunction
is called:
class Test<T> where T : struct, IConvertible
{
private static Func<int, T> _getInt;
static Test()
{
var param = Expression.Parameter(typeof(int), "x");
UnaryExpression body = Expression.Convert(param, typeof(T));
_getInt = Expression.Lambda<Func<int, T>>(body, param).Compile();
}
public static T TestFunction(T x)
{
int n = Convert.ToInt32(x);
T result = _getInt(n);
return result;
}
}
Code from Convert
class, IConvertible
interface and Generics performance comparison test