I am using C# 6.0 to create getters and setters of properties in a class like this:
private int _id { get; set; }
public int Id => _id;
But the compiler says:
Property or indexer 'Id' cannot be assigned to -- it is read only
How can I fix it without creating getters and setters like this:
private int _id { get; set; }
public int Id
{
get { return this._id; }
set { this._id = value; }
}
Shorthand syntax with => only constructs a read-only property.
private int _id;
public int Id => _id;
This is equivalent to auto-property which is read-only:
public int Id { get; }
If you want your property to be both settable and gettable, but publically only gettable, then define private setter:
public int Id { get; private set; }
That way you don't need any private field.
With
private int _id { get; set; }
you are creating a property _id
with a getter and a setter.
With
public int Id => _id;
You are creating a property Id
that has only a getter and returns the value of property _id
I think you are mixing up how to take advantage of automatic properties, because this
private int _id { get; set; }
public int Id
{
get { return this._id; }
set { this._id = value; }
}
creates two properties: _id
with auto-generated getter/setter and Id
with explicit getter/setter that just call the corresponding getter/setter of _id
.
Without the automatic property feature, you had to write this:
private int _id;
public int Id
{
get { return this._id; }
set { this._id = value; }
}
Here, _id
is a field and Id
is a property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With