views:

90

answers:

4

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/

+10  A: 

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.

Reed Copsey
+1  A: 
public object Property { get; private set; } 

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

Robert Harvey
A: 

From the C# spec:

Because the backing field is inaccessible, it can be read and written only through the property accessors, even within the containing type.

Leaving one of the accessors out would mean that the property would either be read-only or write-only, even within the constructor of the class/struct. Not very useful.

Andrew Cooper
+1  A: 

How could you use a property such the following?

public object Property { get; }

Theoritically if you could write something like that it always returns null as it lacks to the set accessor. I think it is useless unless you set the hidden field in some way to have a static value to always return it.

A_Nablsi