'Type Confusion' happens when we are are able to cast an Class A object into a Class B type, without triggering an compilation or runtime error. Under normal behaviour, we would get an compilation error since Class A and Class B are not compatible classes.
We are basically trying to do this (which breaks 'type safety'):
String a = "";
StringBuilder b = (StringBuilder) a;
Here is a C# code sample that shows a number of examples around an specific Type Confusion scenario:
Extension method used:
Code that creates the DLL which does the type confusion:
Here is a different example where I was able to cast an TextBox as a Label:
Although we can can cast any object into any type, if the memory values don't align, we will end up crashing the runtime :)
For example, casting a TextBox as a ToolStripTextBox
Triggered this error:
And this one:
So yeah, we have to be careful, but I already have a number of places I can use this technique inside the O2 Platform (for example when reusing dynamically compiled objects which from the CLR point of view are created in different assemblies, and are treated as incompatible)
Related Posts: