Skip to content

Instantly share code, notes, and snippets.

@Porges
Created January 23, 2019 21:47
Show Gist options
  • Save Porges/e66f90eb9a5781498c11811d7ad28aab to your computer and use it in GitHub Desktop.
Save Porges/e66f90eb9a5781498c11811d7ad28aab to your computer and use it in GitHub Desktop.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
class Program
{
static void Main()
{
var x = new Person();
Console.WriteLine(x.GetType());
ReallyUnsafeSetType(x, typeof(Dog));
Console.WriteLine(x.GetType());
}
unsafe static void ReallyUnsafeSetType(object it, Type t)
{
// just need it for its typecode, so don't bother initing
var target = FormatterServices.GetUninitializedObject(t);
// treating as string lets us pin, it's a magic type
// otherwise you can only pin blittable types
fixed (char* cIt = Unsafe.As<string>(it))
fixed (char* cTarget = Unsafe.As<string>(target))
{
// copy across typecode (lives 3 ints before first character)
*(((int*)cIt) - 3) = *(((int*)cTarget) - 3);
}
}
}
class Person { }
class Dog { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment