Resharper is suggesting I change the following code to an auto-property. Can anyone explain why this would be better?
private List<Configuration> _configurations;
public List<Configuration> Configurations
{
get { return _configurations; }
set { _configurations = value; }
}
To:
public List<Configuration> Configurations { get; set; }
Why is it okay to do this to primitive types but suggests this way for object types?
Consider both equivalent pieces of code:
private List<Configuration> _configurations;
public List<Configuration> Configurations
{
get { return _configurations; }
set { _configurations = value; }
}
and
public List<Configuration> Configurations { get; set; }
To a reader, assuming she is knowledgeable of C#, the second piece code is very quick to read. The first one takes longer and does not add any information. In fact, it adds useless information: I have a property Configurations
, but I also have an equivalent field _configurations
, and the code in the rest of the class may use any of them, so I have to take them both into account. Now imagine your class has fifteen properties like this one, for instance. Using automatic properties you greatly reduce complexity for whoever is reading the code.
Besides, if you consistently use automatic properties, whenever you write a non-automatic one the reader is warned immediately that there is something going on there. This useful information is hidden if you don't use automatic properties.
In summary, consistent use of automatic properties:
What's not to like?
The behaviour between both codes is the same, auto properties are just syntax sugar to make properties without logic easier to read.
See the MSDN documentation for more explanations :
In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors.
I guess re-sharper has determined that an auto-property would be better here as your code is simply getting and setting a backing variable, in the same way that an auto-property would do.
Had re-sharper detected that your getter and setter were going more than just assigning to and reading from the backing variable, my assumption is that it would not be an issue.
I'm not a fan of re-sharper, for various reasons. I prefer using StyleCop and Code Analysis (FXCop), however it has it's benefits in that it can help make your code more readable and maintainable. That's all its trying to do here really.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With