1

Possible Duplicate:
Is a Java static block equivalent to a C# static constructor?

Is there an equivalent to:

public class people {
    private static int x; 
    //... 
    static {
        x  = 3; 
    }
}

of JAVA in C#.NET?

Community
  • 1
  • 1
The Mask
  • 17,007
  • 37
  • 111
  • 185

2 Answers2

10

Yeah, it looks mostly the same

public class People
{
    private static int x;
    static People()
    {
        x = 3;
    }
}

but you could also do this:

public class People
{
    private static int x = 3;
}
McKay
  • 12,334
  • 7
  • 53
  • 76
  • :) - you obviously type faster than I do :) – Shaun Wilde Nov 11 '11 at 00:01
  • 9
    Note that there are extraordinarily subtle differences regarding when you are guaranteed that the field is initialized depending on whether the initialization is inside or outside the cctor, and whether or not there is a cctor. See Jon's article on the subject if you are interested. http://csharpindepth.com/Articles/General/Beforefieldinit.aspx – Eric Lippert Nov 11 '11 at 00:05
4

you can use a static constructor

static people()
{
  x= 3;
} 

see http://msdn.microsoft.com/en-us/library/k9x6w0hc(v=vs.80).aspx

or you can just initialise it as-is

private static int x = 3;
Shaun Wilde
  • 8,228
  • 4
  • 36
  • 56