Breaking the CLR Type Safety; Part two

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.

Msdn has a example which shows this restriction. If you violate this, you’ll get compiler error CS1540

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.

Advertisements

Breaking the CLR Type Safety

As you might have already heard .Net is type safe. Specifically talking CLR provides type safety at runtime, some .Net languages (example: C#) work with CLR to provide type safety at compile time.

So what does the term type safe mean?

Let’s find what Wikipedia says:

In computer science, type safety is the extent to which a programming language discourages or prevents type errors. A type error is erroneous or undesirable program behavior caused by a discrepancy between differing data types for the program’s constants, variables, and methods (functions), e.g., treating an integer (int) as a floating-point number (float). Blah blah blah..

Ok, Now we know that type safety has something to do with preventing the programmer from accessing the type as other than what it is.

Well, C# and CLR are pretty good in this, they work together to push you into the Pit of success. But, you need to be very careful when working with unsafe code. Unsafe code is a different world in which you lose all the type safety, memory safety, security etc. So, clearly chances of making mistakes in unsafe code is greater than safe code(code which doesn’t uses unsafe).

We’re not going to look at unsafe code here. There is one trap I can see without using unsafe code at all. It is not so common, but there it is.

You probably have learned union in academics while learning C and C++, but, in C# you probably don’t need this if you’re writing pure managed code, no Interop.  Some of you might not even know that union do exist in .Net world, but they do exist.

I write managed code, To be honest, I’ve never found a use case for union in .Net(at the time of writing), I mean pure managed code, no Interop.

What this post has to do with Union?  As we know that unions share same memory location to store multiple fields(one at a time), that’s where the trap is. Yes, CLR won’t stop you falling into the trap in this case, i.e you could break the type safety provided by CLR using unions. May be break isn’t the right word,  you could call it as a caveat to be aware of. It doesn’t matter what you call, but there’s something to be aware of.

In above program we create a new instance Union and set the Builder field to new StringBuilder. We’re not creating any  instances of String and assigning to Text field, but you can access it. That’s the beauty of unions.

We’re interpreting the StringBuilder as if it is String which also means that something terribly went wrong.

Ideally as a managed programmer you would expect CLR to throw InvalidCastException but above program erroneously  prints some number as String.Length and StringBuilder as the type of the object. If you recall, this clearly violates the definition of type safety from Wikipedia which we skimmed earlier.

Summary

This is not to say that CLR isn’t type safe rather it is possible to write erroneous code with C# even without unsafe context. So be careful while dealing with unions in .net.