Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can a read only property be assigned via constructor?

Tags:

c#

I've set property Name is read only, but it can still be assigned.

class Person
{
    public string Name { get; }
    public Person(string name)
    {
        Name = name;
    }
}

Try to set value to property Name:

var p = new Person("Kevin");            
Console.WriteLine(p.Name); //output: Kevin
p.Name = "John"; //Property or indexer 'Person.Name' cannot be assigned to -- it is read only

Can you explain me why?

like image 682
Tân Avatar asked Dec 05 '22 19:12

Tân


1 Answers

It can only be assigned in the constructor or in the initializer for the property declaration - just like a read-only field can only be assigned in the constructor or in the field initializer.

There won't be a property setter generated - the compiler will use a read-only field, and initialize it in the constructor. So the generated code will be broadly equivalent to:

class Person
{
    private readonly string _name;

    // Old school: public string Name { get { return _name; } }
    public string Name => _name; 

    public Person(string name)
    {
        _name = name;
    }
}

It's enormously useful to be able to do this, and I'm really glad it was added to C# 6.

like image 123
Jon Skeet Avatar answered Dec 22 '22 14:12

Jon Skeet