Reputation: 329
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.
Upvotes: 2
Views: 91
Reputation: 2753
If you want to update your code to newer syntax the equivalent is:
public SomeValue { get; private set; }
Regards
Upvotes: 2
Reputation: 127543
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.
Upvotes: 2
Reputation: 141
If you use this auto property, what can you do if you want to change that value during program running?
Upvotes: 1