Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a technical reason why an automatic property must define both a get and set accessor

I know that automatic properties must define a get and set accessor method, I also know that it is possible for either of these accessors to be made invisible by means of an access modifier.

Is there a technical reason why the compiler is happy with

public object Property { get; set; }

but not

public object Property { get; }

My (possibly wrong) understanding of this code is that the compiler generates a backing field that is hidden from the calling code like so:

private object hiddenField; //hidden by compiler.

public object Property

{

get { return hiddenField; }

set { hiddenField = value;}

}

If the compiler can generate that, is there a reason that it can't omit the set accessor function based on the presence (or lack thereof) of a setter in the property declaration.

I understand that this may be an issue of feature scope rather than a technical limitation, I also freely admit that I have not yet consulted the C# language specification as yet.

[UPDATE 2]

Forgive me...I'm an idiot :P, I see now, thank you everyone for tollerating my senior moment/

like image 595
Crippledsmurf Avatar asked Dec 13 '22 18:12

Crippledsmurf


1 Answers

Without the set accessor, there is no way to set the value, since you don't have a way to access "hiddenField".

Similarly, without a get accessor, there would be no way to get back a value you set.

Since it really becomes useless, it's not allowed.

However, you can have different accessibility on the two methods:

public object Property { get; private set; }

This provides you the ability to hide the set from outside, but still have a usable property.

like image 97
Reed Copsey Avatar answered Jan 25 '23 23:01

Reed Copsey