Reputation: 33
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?
Upvotes: 3
Views: 460
Reputation: 711
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.
Upvotes: 2
Reputation: 2732
The concept of using readonly is - you can assign the value while initilization only, not after that. That's why it says - readonly.
The private set is having a different picture, it allows you to modify the value at any point of time but within class level only.
Hope this clears your doubt.
Upvotes: 3
Reputation: 65077
No.
Private set means you can change the value of the member anywhere in the class. Readonly with set means it can only be set in the constructor, thereby guaranteeing it isn't changed anywhere else.
Upvotes: 3