Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generics and casting

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);
}
like image 675
JL. Avatar asked Nov 29 '22 16:11

JL.


1 Answers

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).

like image 184
Yngve B-Nilsen Avatar answered Dec 01 '22 07:12

Yngve B-Nilsen