Expression properties versus {get; set;}

When I have Visual Studio 2017 generates properties for me, it will always use the new properties associated with the expression, for example:

private static string username;
internal static string Username { get => username; set => username = value; }

      

Is there any advantage to using this style in the following, or is it just a matter of preference and readability?

internal static string Username { get; set; }

      

+3


source to share


3 answers


Several advantages that I can quickly see in the second style:

  • You enter less.
  • Reads quickly.
  • Doesn't make the reader think that the getter or setter is doing something special.
  • Find all links returns fewer results.
  • The expression equalizer is not triggered by the compiler.


Edit

I missed one major problem with the first style. See answer below.

+2


source


Expression syntax with expression is useful in the following cases:

Get or set only a property

public DateTime Date => DateTime.Now;

      

Methods



public IEnumerable<string> GetData => SomeMethodThatReturnData.Select(x => x.Name);

      

And a constructor with 1 input parameter

public SomeClass(IRepository repository) => _repository = repository;

      

+2


source


Yes, there is a difference; great really. Your previous solution will create an infinite loop because the getter and setter property is referencing itself.

string Username { get => Username; set => Username = value; }

      

This is strictly equivalent to the following (with its just syntactic sugar):

string Username
{
    get
    {
        return Username;
    }
    set
    {
        Username = value;
    }
}

      

So the getter and setter for a property Username

refer to an element Username

that is itself. Therefore, when you access a member, he will constantly call himself forever and never get a result.

You should probably do the following:

string _username;
string Username { get => _username; set => _username = value; }

      

You now have a backing field that you reference to actually store the property value. This works great and there is no difference with the more verbose getter and setter syntax. It compiles to the same thing; its just that C # 6 allows you to make it a little easier.

The remaining difference is an explicit backing field and a backing field that is automatically generated when using an automatic property. If you want to use the auto property, it depends a little on your style, but in general there is no real reason not to use them if you are going to create the same background field otherwise manually. Of course, unless you store the value in an equal backing field and / or need some extra logic, then you certainly cannot use auto properties here. But then you probably won't end up having expression related properties. See also this question about auto properties.

+1


source







All Articles