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.
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.