Bhavya

Code -> Break -> Fix -> Blog

C# 6.0 : Getter-Only Auto-Property

1 Comment

Lets first discuss what would have lead to having this feature.

Problem: We want to have a read-only field and a property which encapsulates it.

In the previous version, this is what we would do:

private readonly int myProperty;

public int MyProperty
 {
 get
 {
 return myProperty;
 }
 }

The value of myProperty (because it is read-only) can only be set in the constructor.

Let’s try to achieve this with C# version < 6.0.

 internal class MyClass
 {
 public int MyProperty { get; }
 }

The above code will give the following error:

‘MySolution.MyClass.MyProperty.get’ must declare a body because it is not marked abstract or extern. Automatically implemented properties must define both get and set accessors.

Using C# 6.0:

 internal class MyClass
 {
 public int MyProperty { get; }
 }

The above code will generate a backing read-only field. As it is a read-only field we can set the value of this property in the constructor.

 public MyClass()
 {
 MyProperty = 100;
 }

We can also initialize the Auto-Property as below:

public int MyProperty { get; } =10;

If we try to access it in any class operation then we get compile time error.

 public void MyMethod(int passedValue)
 {
 MyProperty = passedValue;
 }

Error : Property or indexer ‘MyClass.MyProperty’ cannot be assigned to — it is read only

Getter-only Auto-Property will help the developer to write just 1 line of code instead of 4-5 lines.

Let me know your thoughts.

~BS

Twitter Logo

Advertisements

One thought on “C# 6.0 : Getter-Only Auto-Property

  1. Pingback: New Features of C# 6.0 | Bhavya

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s