CSharp - Create expression-bodied properties

Introduction

Suppose that you have a read-only property like this:

class MyClass
{
        private double radius = 10;
        public double Radius
        {
            get { return radius; }

        }
}

You can rewrite the code using expression-bodied properties like in the following:

class MyClass
{
        private double radius = 10;
        //Expression bodied properties (C#6.0 onwards)
        public double Radius => radius;
}

You can see that the two braces and the keywords get and return are replaced by this symbol '=>'.

We can use property initializers like following:

public int MyInt2{
    //automatic property declaration
    get; set;
} = 25;//Automatic initialization

The code above initialized Myint2 with the value 25.

We can also make it read-only by removing the set accessor.

To check your language version, you can go to Project Properties then Build then Advanced Build Settings and then Language version.

Related Topic