C# 6 features – Auto-property initializers 1

Getter-only auto-property

facebooktwittergoogle_pluslinkedinmail

Properties were always a more powerful version of fields. But sometimes you just want them to behave the same and the concise notation was not available. It’s fixed in C# 6.

Let me start with a short history of properties syntax in C#. In early C# times there was only one way to declare them – very explicit:

        private string _name = "Joe"; // backing field
        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

There was a little improvement introduced in C# 3 – Auto-implemented properties. Basically the need to create backing field was left for compiler.

        public string Name { get; set; }

But still it was a bit cumbersome if you wanted to initialize property. You could either use old explicit syntax or do it in constructor.

        public string Name { get; set; }

        public MyClass()
        {
            Name = "Joe";
        }

Not perfect and not nice, especially if you want to do a simple initialization, like the above. The C# 6 release serves well here. You can now initialize property inline. It’s concise and readable.

        public string Name { get; set; } = "Joe";

Important to know is that the initializer sets the backing field directly, so the auto-property setter is not used.

Property initializers work similar to field initializers:

  • Are executed in declaration order (along with field initializers)
  • Can’t reference this  as are executed before object is initialized (before constructor is called)

 

Getter-only auto-properties

It was always possible to create getter-only properties, but the auto-property syntax had not sense for getter-only case. Compiler didn’t know where it should take value from. C# 6 added auto-property initializers and now it makes sense to use it with getter-only properties.

        public string Name { get; } = "Joe";

The backing field of getter-only auto-property is declared as read-only. It can be initialized by auto-property initializer or in constructor. In both cases value is assigned directly to backing field.

        public string Name { get; } = "Joe";

        public MyClass(string name)
        {
            if (!string.IsNullOrEmpty(name))
            {
                Name = name;
            }
        }

At front auto-properties were shorthand available only if you were willing to make class mutable. Now, getter-only auto-properties are shorthand for immutable approach. The support for mutable and immutable properties have been leveled.

 

facebooktwittergoogle_pluslinkedinmail

Leave a comment

Your email address will not be published. Required fields are marked *

One thought on “C# 6 features – Auto-property initializers