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

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

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;
Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

One Comment to “Initialize Auto-Property and Getter Only Auto-Property in C# 6.0”

Comments are closed.