Created
January 7, 2014 19:48
-
-
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.
This file contains hidden or 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
/// <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