", Why both of these Code have the same result ) public class Infor<TFirst, TSecond, TThird> { private TFirs..." /> ", Why both of these Code have the same result ) public class Infor<TFirst, TSecond, TThird> { private TFirs..." /> ", Why both of these Code have the same result ) public class Infor<TFirst, TSecond, TThird> { private TFirs..."/>

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

124 Views Asked by At

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; } }
}
3

There are 3 best solutions below

0
On BEST ANSWER

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.

0
On

There are differences in the compilers that can handle it.

Expression bodied property accessors is a C# 7 feature. So, the C# 6 compiler, for example, will consider it an error.

0
On

There is no difference between these two code samples. This also works with functions, if you have only one internal operation with result that can be immediately returned from function. For example:

int Method(int x)
{
    return x;
}

Is equivalent to:

int Method(int x) => x;