views:

843

answers:

4

In C#, if I declare an auto-implemented property, why do I have to declare BOTH the get and set part?

i.e.

public string ThisWorks { get; set; }

public string ThisDoesnt { get; }

Isn't this just syntactic sugar - i.e. the compiler inserts a private field for the property? So why the problem?

Curious.

+25  A: 

If you didn't have a setter - then how would you ever set the property?

Incidentally, you can specify the accessibility, eg:

public string Foo
{
  get;
  private set;
}
stusmith
+10  A: 

An auto-implemented property has no accessible private store, so you would have no way to set the value without a setter, making it totally useless.

GalacticCowboy
+9  A: 

Without a setter, you would never be able to provide a value - as you don't have any way of specifying the backing variable's name.

I've requested a readonly automatic property, declared like this:

public string ReadonlyProperty { get; readonly set; }

which would create a readonly backing variable, a property with only a getter, and translate all calls to the setter into direct access to the variable. You could only call the setter within the constructor - just like for normal readonly variables.

We'll see whether this request does any good... it's a real shame it's not in there at the moment, as it makes it harder to implement immutable types than mutable types :(

Jon Skeet
What would this provide that: "public readonly string ReadonlyProperty" would not other than the ability to break point on accessing the property?
Jeff Yates
@ffpf - public readonly string Blah; <-- that's not a property, that's a field. You need a get/set to be a "property". Fields aren't picked up on things like databinding, property-grids, etc. They have a different semantic meaning.
Timothy Khouri
See http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx for why I don't like exposing public fields other than *sometimes* constants.
Jon Skeet
VB 10 might get this: "ReadOnly Property MaxItems As Integer = 100"
Jonathan Allen
@jon: Thanks, that makes a lot of sense. I hadn't considered the serialization or ref points.@Timothy: I understand the difference. That wasn't the point I was making in this instance. Thanks.
Jeff Yates
+3  A: 

You need a set - otherwise, how does your auto-implemented property get its value? When auto-implementing the property, you have to have a set accessor to at least give it a value during construction.

Jeff Yates