3
votes

The following code does not call the class static constructor. Is this a bug or feature?

class Test
{
    static Test
    {
       //do stuff
    }
    public static AnotherClass ClassInstance { get; set; }
}

class Program
{
    public static void Main()
    {
        var x = Test.ClassInstance;
    }
}

I don't have a compiler right now, but this is what happened to me today. The static constructor is never called, but it is called when ClassInstance is a field instead.

EDIT: I understand that static constructor is called when first instance is created or a field is accessed. Isn't there a field behind the automatic implemented property?

I am looking for some explanation on why the property does not trigger static constructor when property is implemented as two functions and one field. It is just very unlogical to me and that is why I thought it could be a bug.

4
I just compiled and ran your code. The static constructor does get called.Joe Daley
@Joe what framework are you targeting?Simone
@Simone I tried targeting every framework available in VS2010 (namely 2.0 and higher) and it works the same in all.Joe Daley
I see, I'm using SharpDevelop and the exhibited behaviour is the same as the OP.Simone
I was using vs2008 and .net 3.5leiz

4 Answers

1
votes

Static constructors invoked the first time an instance of a class are created or when a static member is referenced. So the first time your create an instance of Test or when the ClassInstance property is referenced is when your static constructor will be called.

Would you like to know more? - http://msdn.microsoft.com/en-us/library/k9x6w0hc(VS.80).aspx

1
votes

I verified the same behaviour, but if you change the code like this:

class AnotherClass {}

class Test
{
    static Test()
    {
        Console.WriteLine("Hello, world!");
    }

    public static AnotherClass ClassInstance { get { return new AnotherClass(); } }

}

class Program
{
    public static void Main()
    {
        var x = Test.ClassInstance;
    }
}

it writes "Hello, world!"...

1
votes

Static constructor is called when any static member is accessed or instance is created

class Program
{
    static void Main(string[] args)
    {
        A.SomeField = new B();
    }
}

class A
{
    static A()
    {
        Console.WriteLine("Static A");
    }

    public static B SomeField { get; set; }
}

class B
{
    static B()
    {
        Console.WriteLine("Static B");
    }
}

Result:

Static B
Static A

As you see - there is no "Static B" in the result

0
votes

the static constructor is called automatically before the first instance is created or any static members are referenced.

more information from Msdn.