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.

Duncan
  • 10,218
  • 14
  • 64
  • 96

5 Answers5

29

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
  • 14,003
  • 7
  • 56
  • 89
12

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • What would this provide that: "public readonly string ReadonlyProperty" would not other than the ability to break point on accessing the property? – Jeff Yates Dec 03 '08 at 14:30
  • @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 Dec 03 '08 at 14:36
  • See http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx for why I don't like exposing public fields other than *sometimes* constants. – Jon Skeet Dec 03 '08 at 14:37
  • VB 10 might get this: "ReadOnly Property MaxItems As Integer = 100" – Jonathan Allen Dec 04 '08 at 01:00
  • @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 Dec 04 '08 at 22:02
11

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
  • 11,663
  • 2
  • 41
  • 66
3

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
  • 61,417
  • 20
  • 137
  • 189
0

Interestingly, the new Roslyn compiler in Visual Studio 2015 now allows this, even if the project is configured to use C# version 5.

Wim Coenen
  • 66,094
  • 13
  • 157
  • 251