Let’s say I have 2 properties
public readonly list<int> numberListReadonly { get; set; }
public list<int> numberListPrivateSet { get; private set; }
For those property I can have a constructor / private function in Foo, I can initiate those list without error
public Foo()
{
numberListReadonly = new list<int>();
numberListPrivateSet = new list<int>();
}
public void FooInside()
{
numberListReadonly = new list<int>();
numberListPrivateSet = new list<int>();
}
When I access from outside of the class
void FooOutside()
{
Foo.numberListReadonly = new List<int>();
Foo.numberListPrivateSet = new List<int>()
}
The compiler throws error, which is expected.
“Foo.numberListReadonly cannot be assigned to — it is readonly”
“Foo.numberListPrivateSet cannot be assigned to — it is readonly”
I do a search it seems that the “common practice” is to use private set on “readonly” property with the ability of “set” within the class
So is an explicit readonly property with set & get equivalent to get & private set?
No they are different. The readonly modifier in C# exists typically to mark a field (not property) as readonly. This attribute allows a field value to be set in the constructor of the same class.
The recommended method for a true readonly property is to omit the setter. A private setter simply indicates that the property cannot be set outside of the class.