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:
public static T InternalData<T>(object data)
{
return (T) Convert.ChangeType(data, typeof(T));
}
This works for types that implement the IConvertible
interface (which Int32
and String
does).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With