Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# 6 getters and setters

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; }
}
like image 752
Lucas Avatar asked Dec 09 '16 18:12

Lucas


2 Answers

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.

like image 105
Zoran Horvat Avatar answered Sep 30 '22 00:09

Zoran Horvat


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.

like image 42
Sentry Avatar answered Sep 30 '22 00:09

Sentry