Search code examples
c#.netcompiler-constructionroslyn.net-runtime

Are there any differences when using Property "get {}", "set {}" or "=>" syntax in C#?


Code_1 ( This code is using "=>", Why both of these Code have the same result )

public class Infor<TFirst, TSecond, TThird>
{
    private TFirst first;
    private TSecond second;
    private TThird third;

    public TThird Third { get => third; set => third = value; }
    public TSecond Second { get => second; set => second = value; }
    public TFirst First { get => first; set => first = value; }
}

Code_2 ( This code is using "return" not "=>" )

public class Infor<TFirst, TSecond, TThird>
{
    private TFirst first;
    private TSecond second;
    private TThird third;

    public TThird Third { get { return third; } set { third = value; } }
    public TSecond Second { get { return second; } set { second = value; } }
    public TFrist First { get { return first; } set { first = value; } }
}

Solution

  • No there are no differences. Internally C# compiler converts MyProperty { get { or set { syntax to compiler emitted methods with the following signatures and implementations:

    TFirst get_MyProperty() { return first;}
    void set_MyProperty(TFirst value) { first = value; }
    

    The very same happens for => syntax which is called expression bodied property accessors. Usage of => is a merely a syntactic sugar which was created to simplify coding and reduce boilerplate code which has to be repetitively written.