views:

267

answers:

2

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.

+9  A: 

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.

Andrew Hare
+1 - agreed. I'd recommend the wrapper for a simple reason: Clarity.
Frank V
but hackish execution time reflection is so much more fun! This is probably going to be temporary code anyways. Once the project is complete, it probably wont be necessary to keep it.
Matthew Ruston
+1 for better ways to achieve this behavior.
JaredPar
+5  A: 

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.

JaredPar
+1 For pointing out that it isn't even possible - I address the motivations more that the feasibility of the endeavor!
Andrew Hare