Is there a technical reason why an automatic property should determine both get and set accessor

I know that automatic properties must be determined by the get and set accessor methods, I also know that any of these accessories can be made invisible using an access modifier.

Is there a technical reason why the compiler is satisfied

public object Property { get; set; } 

but not

 public object Property { get; } 

My (possibly incorrect) understanding of this code is that the compiler creates a support field that is hidden from the calling code like this:

 private object hiddenField; //hidden by compiler. public object Property { get { return hiddenField; } set { hiddenField = value;} } 

If the compiler can generate this, is there a reason why it cannot omit the set accessor function based on the presence (or absence thereof) of the setter in the property declaration.

I understand that this may be a problem of the scope of possibilities, and not a technical limitation, I also freely admit that I have not yet specified the C # language specification.

[ UPDATE 2 ]

Forgive me ... I'm an idiot: P, now I see, thanks to everyone for changing my senior moment /

+4
source share
4 answers

Without an installation accessory, it is not possible to set the value, since you do not have access to "hiddenField".

Similarly, without the get accessor, there will be no way to return the value you set.

Since it is really useless, it is not allowed.

However, you can have different availability by two methods:

 public object Property { get; private set; } 

This gives you the ability to hide the set from the outside, but still has a useful property.

+11
source
 public object Property { get; private set; } 

will work, and it will have the semantics that you expect.

+1
source

How can you use a property, for example the following:

public object Property { get; }

Theoretically, if you can write something like this, it always returns null, because it lacks the set access. I think this is useless unless you set the hidden field in any way so that it always returns a static value.

+1
source

From the C # spec:

Since the support field is not available, it can be read and written only through the ownership of accessories, even within the containing type.

Exiting one of the accessories means that the property will be either read-only or write-only, even inside the class / structure constructor. Not very helpful.

0
source

All Articles