I’ve come across a function in our code base throwing an error:
public static T InternalData<T>()
{
return (T)"100";
}
Obviously I’ve simplified the code and added the “100” as a literal string value. T is of type int.
It throws a:
System.InvalidCastException: Specified cast is not valid.
It seems that you can’t implicitly convert a string to int in C#, how can I fix this code so that it can handle converting any generic type?
The actual code would look something like this:
public static T InternalData<T>()
{
return (T) something (not sure of type or data);
}
Try:
This works for types that implement the
IConvertibleinterface (whichInt32andStringdoes).