Getter Only Auto-properties in C# 6.0

Description

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

Content

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 a new feature in C# 6.0 called "Getter only auto-properties".

This feature allows us to create a read-only property with just a get, no set. 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" in the "program.cs" and build the application.

Code

  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.   
  6.         }  
  7.     }  
  8.   
  9.     public class MyClass  
  10.     {  
  11.         public int MyProp { get; }  
  12.   
  13.     } 

I will get a successful build.



But when I write the same code in Visual Studio 2012 that works with C# 5.0, it gives me an unsuccessful build due to an error.



In C# 6.0, when we write a property only with "get", it automatically becomes a Read Only property. For more explanation I am writing an example with some code where we declare a property with only a "get", assign a value in it and access it with the object of that class.

Code

  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             MyClass obj = new MyClass();  
  6.             Console.WriteLine(obj.MyProp);  
  7.             Console.ReadKey();  
  8.         }  
  9.     }  
  10.   
  11.     public class MyClass  
  12.     {  
  13.         public int MyProp { get; }  
  14.   
  15.         public MyClass()  
  16.         {  
  17.             MyProp = 10;  
  18.         }  
  19.     } 




But when I set a value of that property again, it gives the error and says it's a read only property.



Conclusion

Now you understand the new feature of C# 6.0 that allows to use the "Getter Only Auto – Properties".


Similar Articles