Can a class have static constructor?

 Posted by Tripati_tutu on 11/15/2010 | Category: C# Interview questions | Views: 3854 | Points: 40
Answer:

Yes, a class can have static constructor. Static constructors are called before when any static fields are executed. These are used to initialize static class members and called automatically before the first instance is created or any static members are referenced. This is also known as before instance constructor. Below is one example of above described theory.

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SampApp
{
class Sample
{
static int i;
static Sample()
{
i = 10;
Console.WriteLine("In Static Constructor");
}
public Sample()
{
Console.WriteLine("In Instance Constructor");
}
public static void Main()
{
Sample s = new Sample();
}
}
}


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response