I\'m trying to write generic method to cast types. I want write something like Cast.To
instead of (Type) variable
.
My wrong versi
You can do this trick by finding the right methods through Reflection:
public static T To (object obj)
{
Type sourceType = obj.GetType ();
MethodInfo op = sourceType.GetMethods ()
.Where (m => m.ReturnType == typeof (T))
.Where (m => m.Name == "op_Implicit" || m.Name == "op_Explicit")
.FirstOrDefault();
return (op != null)
? (T) op.Invoke (null, new [] { obj })
: (T) Convert.ChangeType (obj, typeof (T));
}
In .NET 4.0, you can use dynamic
keyword as suggested in other answers.