Can we use static constructors to initialize non static members?

 Posted by Ddd on 3/18/2011 | Category: .NET Framework Interview questions | Views: 5784 | Points: 40
Answer:

Yes, it is possible.
But we have to create an object of the class inside the static constructor and then initialize the non static member through the object reference.

Code(example):

class Class2
{
int a;
static Class2()
{
Class2 p = new Class2();
p.a = 45;
System.Console.WriteLine(p.a);
}
static void Main()
{

}
}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Vaishali.fresher on: 3/19/2011 | Points: 10
actually static constructors can access only static members. because when the static constructor is executed only static members are loaded into memory at that time.

Login to post response