3
Vote

Parameterless Constructor in Struct not been called during instance creation

description

Create a new Console Application in VS 2015 Preview and write the following code:
    class Program
    {
        public static List<T> CreateList<T>(int count) where T : new()
        {
            List<T> list = new List<T>();
            for (int i = 0; i < count; i++)
            {
                list.Add(new T());
            }

            return list;
        }
        public struct Point
        {
            public int X { get; set; }
            public int Y { get; set; }
            public int Z { get; set; }

            public Point()
            {
                X = -1;
                Y = -2;
                Z = -3;
            }
        }

        static void Main(string[] args)
        {
            var res = CreateList<Point>(3);
        }
    }

Only the first struct in the list will will have its properties set correctly, other items will have X,Y and Z set to 0.
The constructor is not called at all for those items.
Perhaps .NET has some old optimization that's kicking in and is not aware of parameterless struct constructors.

comments

mdanes wrote Dec 24, 2014 at 9:14 AM

It appears that this is a bug in the framework/runtime, the following code exhibits the same bug:
static void Main() {
    Console.WriteLine(Activator.CreateInstance<Point>().X);
    Console.WriteLine(Activator.CreateInstance<Point>().X);
}