Automated property with getter only, can be set, why?

前端 未结 6 2126
暗喜
暗喜 2020-12-02 16:27

I created an automated property:

public int Foo { get; } 

This is getter only. But when I build a constructor, I can change the value:

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 16:59

    “readonly automatically implemented properties”

    First of all I want to clarify that the property like

    public string FirstName { get; }
    

    Is known as “readonly automatically implemented properties”

    To verify this you can run & check the above code with Visual Studio. If you change the language version from C#6.0 to C#5.0 then compiler will throw the following exception Feature 'readonly automatically implemented properties' is not available in C# 5. Please use language version 6 or greater.

    to change C# language version visit here

    Now I am coming to your second question

    “This is getter only. But when I build a constructor, I can change the value”

    Microsoft introduces the “readonly automatically implemented properties” on the logic of read only. As we know that the keyword “readonly” is available from C#1.0. we use “readonly” keyword as modifier on a field and that field can be assigned in 2 ways either at the time of declaration or in a constructor in the same class.

    In the same way value of “readonly automatically implemented properties” can be assigned in 2 ways

    Way1 (at the time of declaration):

    public string FirstName { get; } = "Banketeshvar";
    

    Way2 (in a constructor in the same class)

    Person()
    {
     FirstName  = "Banketeshvar";
    }
    

    Purely ReadOnly Property

    If you are looking for purely Readonly property then go for this

    public string FullName => "Manish Sharma";
    

    now you cannot assign value of “FullName” propery from constructor. If you try to do that it will throw the following exceptions

    “Property or indexer 'Person.FullName' cannot be assigned to -- it is read only”

提交回复
热议问题