#1,220 – C# 6.0 – Defining a Parameterless Constructor for a struct

In C# 5.0, every struct had a default parameterless constructor that you couldn’t override.  Using the new operator invoked this constructor and all members of the struct were assigned default values.

    public struct MyPoint
    {
        public double X;
        public double Y;
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyPoint pt = new MyPoint();      // default values for X, Y (0.0)
            Console.WriteLine("{0}, {1}", pt.X, pt.Y);
        }
    }

1220-002

In C# 6.0, you can explicitly define a parameterless constructor for a struct, giving non-default values to the members of the struct.

        public struct MyPoint
        {
            public double X;
            public double Y;

            public MyPoint()
            {
                X = 100.0;
                Y = 100.0;
            }
        }

        static void Main(string[] args)
        {
            MyPoint pt = new MyPoint();      // 100.0, 100.0
            Console.WriteLine("{0}, {1}", pt.X, pt.Y);
        }

1220-001