Skip to content

Instantly share code, notes, and snippets.

@derekgates
Created January 7, 2014 19:48
Show Gist options
  • Save derekgates/8305620 to your computer and use it in GitHub Desktop.
Save derekgates/8305620 to your computer and use it in GitHub Desktop.
DynamicCast() casts an unknown type to a given type. This requires .net 4.0 for dynamics.
/// <summary>
/// Dynamically casts a type to another type without knowing the CLR knowing the object's type. Before calling this method,
/// ensure the object's type matches what you are trying to cast to!
/// </summary>
/// <exception cref="System.InvalidCastException"></exception>
public static dynamic DynamicCast(this Type T, dynamic o)
{
return typeof(ReflectionHelpers).GetMethod("Cast", BindingFlags.Static | BindingFlags.NonPublic)
.MakeGenericMethod(T).Invoke(null, new object[] { o });
}
/// <summary>Method used to dynamically cast (through reflection) one type to another type (object to a correct type).</summary>
public static T Cast<T>(object o)
{
return (T)o;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment