Why do automatic properties require both getters AND setters?
-
22-07-2019 - |
Question
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.
Solution
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;
}
OTHER TIPS
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 :(
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.
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.
Interestingly, the new Roslyn compiler in Visual Studio 2015 now allows this, even if the project is configured to use C# version 5.