Created
January 20, 2015 19:48
-
-
Save SriramSakthivel/61c1206dcc11d762d555 to your computer and use it in GitHub Desktop.
Code snippet for the blog post https://sriramsakthivel.wordpress.com/2015/01/11/breaking-the-clr-type-safety-part-two-2/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Base | |
{ | |
protected int state = 123; | |
public int GetState() | |
{ | |
return state; | |
} | |
} | |
public class Derived : Base | |
{ | |
public static void Main() | |
{ | |
Base b = new Base(); | |
//fakeDerived is not Derived,it is same Base instance typed as Derived. | |
Derived fakeDerived = TypeBaseAsDerived(b); | |
fakeDerived.state = 42; | |
Console.WriteLine(b.GetState());//Prints 42 | |
Console.WriteLine(object.ReferenceEquals(b, fakeDerived));//Prints true | |
} | |
private static Derived TypeBaseAsDerived(Base a) | |
{ | |
return new EvilUnion { A = a }.B; | |
} | |
} | |
[StructLayout(LayoutKind.Explicit)] | |
public struct EvilUnion | |
{ | |
[FieldOffset(0)] | |
public Base A; | |
[FieldOffset(0)] | |
public Derived B; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment