Static constructor can run after the non-static constructor. Is this a compiler bug?

Posted by Joe H on Stack Overflow See other posts from Stack Overflow or by Joe H
Published on 2010-05-27T22:58:50Z Indexed on 2010/05/27 23:01 UTC
Read the original article Hit count: 168

Filed under:
|

The output from the following program is:

Non-Static
Static
Non-Static

Is this a compiler bug? I expected:

Static Non-Static Non-Static

because I thought the static constructor was ALWAYS called before the non-static constructor.

I tested this with Visual Studio 2010 using both .net 3.5 and .net 4.0.

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

namespace StaticConstructorBug
{
    class Program
    {
        static void Main(string[] args)
        {
            var mc = new MyClass();

            Console.ReadKey();
        }
    }

    public class MyClass
    {
        public MyClass()
        {
            Console.WriteLine("Non-static");
        }

        static MyClass()
        {
            Console.WriteLine("Static");
        }

        public static MyClass aVar = new MyClass();
    }
}

© Stack Overflow or respective owner

Related posts about c#

Related posts about bugs