简体   繁体   中英

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; }
}

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.

This is the C# 7.0 syntax, just in case you want to keep the private field:

public int Id 
{
   get => _id;
   set => _id = value;
}
private int _id;

Which is very useful for giving full access to some of the properties of a wrapped object:

private Person wrappedObject;

public string Name
{
   get => wrappedObject.Name;
   set => wrappedObject.Name = value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM