Is it possible to create objects returned by a function immutable in C #?

I am writing a function that returns a reference to an object of some encapsulated data structure, and I want no one to be able to modify the object using this link, is it possible to do this in C #?

+6
object immutability c #
source share
3 answers

If the object you return is immutable, this will work fine.

If not, you can return a wrapper object that provides read-only properties.

+8
source share

The only way I can see is to create two interfaces for this type. One interface is read-only. The method then simply returns an instance of this read-only interface.

+1
source share

I do not think there is a built-in way. C # does not seem to support the same const-correctness support as C ++. You can make internal members read-only, and that will be the beginning. But there is more to it than that.

You must execute all the member functions of your non-mutator functions of your class and make all the data element properties w / private seters. When implementing getters for properties, copy all returned classes and return a new instance, instead of returning a link to a private member.

class SomeClass { public void SomeFunctionThatDoesNotModifyState() { } public int SomeProperty { get { return someMember; // This is by-value, so no worries } } public SomeOtherClass SomeOtherProperty { get { return new SomeOtherClass(someOtherMember); } } } 

class SomeOtherClass {// ....}

You need to be very careful that the SomeOtherClass implementation performs a deep copy when invoking the copy constructor.

Even after all this, you cannot guarantee 100% that someone will not modify your object, because the user can hack into any object using reflections.

+1
source share

All Articles