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
- class Program
- {
- static void Main(string[] args)
- {
-
- }
- }
-
- public class MyClass
- {
- public int MyProp { get; }
-
- }
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
- class Program
- {
- static void Main(string[] args)
- {
- MyClass obj = new MyClass();
- Console.WriteLine(obj.MyProp);
- Console.ReadKey();
- }
- }
-
- public class MyClass
- {
- public int MyProp { get; }
-
- public MyClass()
- {
- MyProp = 10;
- }
- }
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".