I’m trying to write a method for coverting a given object to an instance of a given type. I started with this:
private static T TryCast<T>(object o)
{
return (T) o;
}
Going in, I know that isn’t going to work, but it illustrates the concept. Now, I’m going to start having problems when I have types that won’t cast automatically, like string –> DateTime. I was trying to use the Convert Class to deal with these cases, but I just get a compile time error instead of a runtime error. The following code gets the compile error “Cannot cast expression of type ‘string’ to type ‘T’
private static T TryCast<T>(object o)
{
var typeName = typeof (T).FullName;
switch (typeName)
{
case "System.String":
return (T) Convert.ToString(o);
default:
return (T) o;
}
}
I’m also aware of Convert.ChangeType(), but I’m wondering if it will handle edge cases that I would otherwise handle in the above switch, like the stated string –> DateTime that I’d normally just use Convert.ToDateTime for.
private static T TryCast<T>(object o)
{
return (T)Convert.ChangeType(o, typeof(T));
}
So, what is my best option? If somebody can give me a workable approach, I can take it from there.
Convert.ChangeTypeshould handle edge cases; it delegates toIConvertible.To answer the question, the compiler doesn’t know that
Tisstring.Therefore, it doesn’t let you cast between to unrelated types (just like you can’t cast
ButtontoTextBox).You can work around that by casting to
objectfirst:Now, each individual conversion is allowed by the compiler (it’s either a direct upcast or a direct downcast), and you know that the whole thing will work because
TisString.