Initializers For Auto-properties in C# 6.0


In this article I will learn a new feature of C# 6.0 using Visual Studio Ultimate 2015 Preview.


As all we know, Microsoft has launched a new version of C# called C# 6.0 with Visual Studio Ultimate 2015 Preview and there is new feature in C# 6.0 that is called "Initializers for auto-properties".

This feature allows us to initialize a property without using constructor in easy way. Let’s see this feature

I am using Visual Studio Ultimate 2015 Preview.

Open Visual Studio 2015 and select "File" -> "New" -> "Project..." and fill in the project name as "Console Application1".

After creating the project, I will create a class named "MyClass" with a property named "MyProp" only with a "get" and "set" in "program.cs".

Basically we set the property using a constructor like in the following code.


  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  6.         }  
  7.     }  
  9.     public class MyClass  
  10.     {  
  11. public int MyProp { getset; }  
  13. public MyClass          
  14. {     
  15. MyProp=10;          
  16. }  
  18.     } 

And we get the successful build in both, C# 5.0 and 6.0.

C# 5.0 in Visual Studio 2013

C# 6.0 in Visual Studio 2015 Preview

New Feature

In C# 6.0 we can also easily initialize the property with a successful build like in the following code:

  1. public class MyClass  
  2.         {  
  3.             public int MyProp { getset; }=10;  
  4.         } 

But when I write the same code in Visual Studio 2013 that works with C# 5.0, give me the unsuccessful build with an error.

If I initialize the property and print its value using an object of the class, it returns the value which is 10.


Now you understand the new feature of C# 6.0 that allows to use the "Initializers for auto-properties".