Question

Is there any way (utilizing Reflection I hope) that I can make an instantiated object immutable along with all of its public properties? I have a class from someone else's codebase (no source available) that I need to utilize and I basically want an exception to be thrown if any piece of code anywhere tries to call a public setter within this class after it has been instantiated.

Note: I do not want to create a wrapper object around the class in order to implement this. I am lazy.

Was it helpful?

Solution

No there is not via reflection. Type definitions cannot be altered at runtime via reflection and hence it cannot be used as a device to make a type immutable.

But reflection can be used to violate immutability of a type. For instance, it's possible to set properties marked with readonly via reflection long after the constructor has run.

OTHER TIPS

I find it hard to believe that you are willing to introduce reflection code to do something that can be simply solved with a wrapper class.

A small investment of your time now will save you lots of painful time later when your reflection code breaks or requires modification. A wrapper class is simple, easy to implement, is type-safe, and will make sense to other developers down the road. Don't let laziness dictate your architectural choices.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top