Hi, I am confused about what is static constructors in c#.Please help me by giving some suitable examples.
Static constructor is used to initialize static data members as soon as the class is referenced first time. like. Here Int id is a static member. class test { static int id = 5; static test() { id=5; } }
Static constructors are used to initialize static members they are automatically initialize before the instance of class is created.
hi.. A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced. Web Designer | Real Estate Web Design
Static constructor is used to initialize static data members as soon as the class is referenced first time, whereas an instance constructor is used to create an instance of that class with <new> keyword. A static constructor does not take access modifiers or have parameters and can't access any non-static data member of a class.
Static constructor is a special constructor that gets called before the first object of the class is created. It is used to initialize any static data, or to perform a particular action that needs performed once only. The time of execution of static constructor is not known but it is definitely before the first object creation - may be at the time of loading assembly. //Example1 usingSystem; publicClass abc { static abc() { // initialize static members only. } // other methods here. } // Example2 usingSystem; publicclassMyStaticClass { staticint count; staticMyStaticClass() { count =0; Console.WriteLine("Static class is initialized"); } publicstaticvoidMyMethod(string name) { Console.WriteLine("Static class is initialized "+ name); } } MyStaticClass.MyMethod("John");//method call //constructor will be called automatically Output: Staticclass is initialized HelloJohn Key points about static constructor It can only access the static member(s) of the class. Reason : Non static member is specific to the object instance. If static constructor are allowed to work on non static members it will reflect the changes in all the object instance, which is impractical. There should be no parameter(s) in static constructor. Reason: Since, It is going to be called by CLR, nobody can pass the parameter to it. Only one static constructor is allowed. Reason: Overloading needs the two methods to be different in terms of method/constructor definition which is not possible in static constructor. There should be no access modifier to it. Reason: Again the reason is same call to static constructor is made by CLR and not by the object, no need to have access modifier to it
Static constructors are used to initialize static fields in a class. Static constructor is called only once, no matter how many instances you create. Static constructor are called before instance constructors.