C# return a variable as read only from get; set;

Jon picture Jon · Jun 2, 2009 · Viewed 23.2k times · Source

I swear I have seen an example of this but have been googling for a bit and can not find it.

I have a class that has a reference to an object and need to have a GET; method for it. My problem is that I do not want anyone to be able to fiddle with it, i.e. I want them to get a read only version of it, (note I need to be able to alter it from within my class).

Thanks

Answer

Jon Skeet picture Jon Skeet · Jun 2, 2009

No, there's no way of doing this. For instance, if you return a List<string> (and it's not immutable) then callers will be able to add entries.

The normal way round this is to return an immutable wrapper, e.g. ReadOnlyCollection<T>.

For other mutable types, you may need to clone the value before returning it.

Note that just returning an immutable interface view (e.g. returning IEnumerable<T> instead of List<T>) won't stop a caller from casting back to the mutable type and mutating.

EDIT: Note that apart from anything else, this kind of concern is one of the reasons why immutable types make it easier to reason about code :)