Skip to content

Instantly share code, notes, and snippets.

@SriramSakthivel
Created January 20, 2015 19:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SriramSakthivel/61c1206dcc11d762d555 to your computer and use it in GitHub Desktop.
Save SriramSakthivel/61c1206dcc11d762d555 to your computer and use it in GitHub Desktop.
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