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