This is because there is a private setter
which only works inside the class constructor. See the docs.
Example when implicitly defined
public string FirstName { get; private set; }
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
see a sample example which i am running on version 4.5.2. in this program i can assign ready only property with a value from constructor....why it is allowing ?
public class Person
{
//line 1
public string FirstName { get; }
//line 2
//public string LastName { get; } = null!;
//assign null is possible
//public string? MiddleName { get; } = null;
public Person(string firstName, string lastName, string middleName)
{
FirstName = firstName;
//LastName = lastName;
//MiddleName = middleName;
}
public Person(string firstName, string lastName)
{
FirstName = firstName;
//LastName = lastName;
//MiddleName = null;
}
}
why program allow assign value to readonly property from CTOR ? please guide me. thanks
This is because there is a private setter
which only works inside the class constructor. See the docs.
Example when implicitly defined
public string FirstName { get; private set; }
Read-only property only work where you create and call an object of a class.
Read-only doesn't work inside your "Person" class.
Therefore, the constructor code below will work normally.
However, changing the value of a read-only attribute is not allowed.
Person oP1 = new Person("AAA", "BBB");
oP1.FirstName = "CCC"; // error CS8370: Feature 'readonly members' is not available ......