Why dotnet program allow readonly property to assign value from Constructor?

T.Zacks 3,976 Reputation points

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

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,922 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Karen Payne MVP 35,006 Reputation points

    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; }  
    1 person found this answer helpful.
    0 comments No comments

  2. Petrus 【KIM】 456 Reputation points

    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 ......
    0 comments No comments