C. Williamson
C. Williamson

Reputation: 329

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.

Upvotes: 2

Views: 91

Answers (3)

Håkan Edling
Håkan Edling

Reputation: 2753

If you want to update your code to newer syntax the equivalent is:

public SomeValue { get; private set; }

Regards

Upvotes: 2

Scott Chamberlain
Scott Chamberlain

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

Wei
Wei

Reputation: 141

If you use this auto property, what can you do if you want to change that value during program running?

A property without a set accessor is considered read-only

Upvotes: 1

Related Questions