Why I can implement a read-only property like so…
public IList<object> SelectedItems { get; }
…and still be able to use its members, like Add, Remove, etc. when I use the property ?
Isn’t readonly supposed to be readonly “all the way down” ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
This isn’t a “readonly” type. It’s a property where you can retrieve the value (the
IList<object>), but can’t set the value to a different instance ofIList<object>as there is no property setter.No. It’s not readonly “all the way down” – the fact that the property only has a getter means you can get the value, but you can do anything you wish with it.
Note that I’d be careful using the term “readonly”. C# has a different, distinct meaning and dedicated
readonlykeyword, which applies only to fields. This isn’t “readonly” in the C# meaning, but a property which only provides a get operation.If you want to have a “read only” list, a good option is to return a
ReadOnlyCollection<T>. For example, if your internal class is aList<T>, you can use:If you are going to do this, it might be better to actually return the
ReadOnlyCollection<T>as well:This way, users won’t expect that it’s safe to call
.Add()on the resulting list.