In my last post we saw that CLR type safety can be broken without using unsafe code. This post heavily depends on my last post. If you have not read it, I recommend you take time to read it and come back.
At this point I assume that you’ve read my last post about “Breaking the CLR Type Safety” with union.
If the last post about type safety isn’t interesting enough, we’ll try something interesting with the same trick mentioned in previous post. Note: This post is not meant to teach something constructive rather to have some fun with the .Net and C# compiler in a interesting way.
Hack Hack Hack…
Warning! If you’re a orthodox developer following etiquette of clean code then definitely this post is not for you. You can stop reading now, I’ll bring you another post later. Others read on, let’s have fun.
We know that
protected keyword in C# will allow us to access the members in the same class or its derived classes. But
protected keyword comes with a restriction that you cannot access the members declared as protected in base class with the instance of base type.
In the above example if you uncomment the line “a.x = 10;” you’ll get CS1540 compiler error because
a is typed as base type, you’re allowed to access the protected member through derived type or the same type only and not from base types.
For someone curious why such restriction exist, here’s Eric Lippert’s answer on the subject.
Now we know that there exist a restriction in accessing
protected members, rest of the post is to show how can we circumvent this restriction in a possibly dirty way which should never be used in any code whatsoever. Purpose of this post is to introduce some problem and solving it to have fun. So don’t take this as a educational post and try to use it.
Let’s say we have a class
Base with field named
state which we’d like to access in its derived class.
I believe no explanation needed. Code is fairly simple,
TypeBaseAsDerived is the magical method which uses the trick explained earlier to Type one type as another evading the type safety. Thus you can access the protected member of base type given that you derived from it using a dirty trick even though it is not allowed.
Those who are tempted to use this as a solution for some problem? No you don’t, there is a better solution to the problem using something so-called Reflection.
I’ve mentioned several times that this post shouldn’t be considered as a guide to write bad code it could be considered as “How not to write code”. Writing such code is different from learning(or knowing) it; nothing wrong in learning it and thus I wrote this post.
Be aware that this is just batshit insane and Don’t try this at Home, Office or anywhere.