Search code examples
c#getter-setterc#-6.0

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

Solution

  • 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.