Expression Bodied Function Members used in get-property

Viewed 234

When writing a class, I can use an Expression bodied function in a Get-property in two ways:

class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}

   public string FullName1 => $"{FirstName} {LastName}";
   public string FullName2 { get => $"{FirstName} {LastName}"; }
}

MSDN about expression bodied function members

You can also use expression-bodied members in read-only properties as well:

public string FullName => $"{FirstName} {LastName}";

So if this syntax represents the implementation of a Get-property, what does the second one mean? What is the difference? Is one preferred above the other?

3 Answers

Those are identical. They compile to the same code:

Person.get_FullName1:
IL_0000:  ldstr       "{0} {1}"
IL_0005:  ldarg.0     
IL_0006:  call        UserQuery+Person.get_FirstName
IL_000B:  ldarg.0     
IL_000C:  call        UserQuery+Person.get_LastName
IL_0011:  call        System.String.Format
IL_0016:  ret         

Person.get_FullName2:
IL_0000:  ldstr       "{0} {1}"
IL_0005:  ldarg.0     
IL_0006:  call        UserQuery+Person.get_FirstName
IL_000B:  ldarg.0     
IL_000C:  call        UserQuery+Person.get_LastName
IL_0011:  call        System.String.Format
IL_0016:  ret         

Just different form of notation, allowing you to also provide set in the same format.

It's a matter of style and readability.

The main advantage of { get => $"{FirstName} {LastName}"; } is that you can combine it with a set {...}.

When you use expression-bodied members with read-write properties, it looks like

public string Property {
    get => field;
    set => field = value;
}

The fact that this syntax is accepted even if you remove the setter is only natural, it would take extra effort to reject that and there is no harm in allowing it. The short form public string Property => field; means exactly the same thing and you are free to choose whichever form you prefer.

Related