If an object is readonly or const, is it possible to cast that object to make it writable?
Something similar to C++ const_cast.
If an object is readonly or const, is it possible to cast that object
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
It’s not possible in C#, just like it’s not possible in C++. In C++, if the object is really const, you cannot
const_castthe constness away and write to it without invoking undefined behaviour:A
readonlyfield in C# only means that the field itself cannot be reassigned. It’s akin toT *constorT&in C++. You can change the referenced object at will through its members.Well, I’m not telling the whole truth. You can cheat and change
readonlyfields through reflection1:If it is a
constfield however, not even this trick will work.constfields are hardcoded in assemblies that use them, instead of keeping references to the original assembly:This means that if you recompile A.dll and change the value of
Foo.Xto 23, B.dll will still use 42 until it is recompiled.All that said, if you want to have a field that you want to change, just don’t make it
readonly. If you want it to be mutable by the class, but immutable from the outside, make it private and add a read-only property (note: this is not the same as areadonlyfield):1This is not really guaranteed, but it works on the Microsoft implementations. If you’re wondering why this hack works at all, you can read Eric Lippert’s explanation. Be sure to also read the answer about
readonlyon value types. And it goes without saying, don’t do this at home.