C. Williamson C. Williamson - 2 months ago 4
C# Question

What is the benefit of using a private member in a get instead of just having the class auto set the property itself?

I see this kind of thing all over the place in our code.

public int SomeValue
{
get { return _someValue; }
}
private int _someValue;


Then, the class sets _someValue and external accessors must use SomeValue to see the value.

What is the benefit of doing this instead of just setting the property to get only and then having the class set SomeValue internally?

public int SomeValue { get; }


Adding the extra private variable seems to just bloat the code.

Answer
public int SomeValue
{
    get { return _someValue; }
}
private int _someValue;

is not the equivalent of

public int SomeValue { get; }

If you do the auto property it is equivalent to

public int SomeValue
{
    get { return _someValue; }
}
private readonly int _someValue;

You can not change the value of _someValue internally with the auto property but you could with the original code.

That being said, based on your comments, the code was most likely written before C# 6 when auto read only properties where introduced and the original author was too lazy or did not know that he could mark _someValue as readonly and did not intend for _someValue to be changed anyway.