Initialize Auto-Property and Getter Only Auto-Property in C# 6.0

By | December 3, 2014

So far we have seen, Property can be initialized only in the constructor, and if it has any backing field defined, that can be initialized where it is declared.   C# 6.0  introduced a new features called “Auto-Property initializer” that allows property to be initialized like fields in the same line where it has been declared.

The following code snippet shows how Auto-Property Initializer works;

public bool MyProperty { get; set; } = false;

With these, MyProperty set to a default value false, without any further initialization.  These makes our code more clean, easily understandable and avoid further deceleration.

Must Read : What’s new in C# 6.0

C# 6.0 also allows us to create getter only Auto-Property as shown below.

public bool MyProperty { get; }

These is a read-only property, and until now we had to use  a private set.  in C# 6.0, without a private set, you can declare a property and initialize the same with Automatic property initializer.

public bool MyProperty { get; } =false;

One thought on “Initialize Auto-Property and Getter Only Auto-Property in C# 6.0

  1. Pingback: Download PPT – “A lap around C# 6.0 and Visual Studio 2015 Preview” – MUGH Dev Day– 29th Nov 2014 | Abhijit's World of .NET

Comments are closed.