I am aware that, static constructors always take precedence and get called first before any instance constructors. However consider the scenario of me having one instance class and one static class. I am wondering why the results are first from Base class and then static class ? I have also verified interchanging calling, I get the result accordingly. But am I wrong in my thoughts that, Static classes always should be called first irrespective of any other instance classes ? Why this raised to me is because, I saw somewhere that, Static classes are loaded automatically when the namespace containing that class is triggered. Then I would expect that static constructor to fire first. Why not it is happening ? Could someone please explain in an understandable and simple way.
public class Base
{
public Base() { Console.WriteLine(" I am from normal Base constructor"); }
static Base() { Console.WriteLine("Hey I am from Static Base"); }
}
public static class Base1
{
static Base1() { Console.WriteLine("I am from Static Constructor"); }
public static void StaticMethod() { Console.WriteLine("I am from Static Method"); }
}
static void Main(string[] args)
{
Base b = new Base();
Base1.StaticMethod();
Console.Read();
}
Static constructors are only called if they are actually needed. If they are needed, they are guaranteed to be called before the normal constructors for their class.
But there is no guarantee that all static constructors will be called before any normal constructor for a different class.
It wouldn’t be possible to do that AND avoid calling static constructors that aren’t used. You could do something like only access a class with a static constructor just before the program terminates, and then only if some condition was satisfied. Clearly, the code couldn’t peer ahead in time to determine whether or not the static constructor call would be needed; therefore, there is no way for it to call the static constructor before your code accesses it.
Check out Eric Lippert’s Blog about Static Constructors for many more details!