Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 986
Jon Avatar asked Jun 02 '09 13:06

Jon


2 Answers

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 :)

like image 142
Jon Skeet Avatar answered Sep 19 '22 08:09

Jon Skeet


Return a reference to a stripped-down interface:

 interface IFoo    string Bar { get; }   class ClassWithGet    public IFoo GetFoo(...); 
like image 33
Anton Gogolev Avatar answered Sep 22 '22 08:09

Anton Gogolev