C # generics and casting

I came across a function in our code base that throws an error:

public static T InternalData<T>() { return (T)"100"; } 

Obviously, I simplified the code and added "100" as a string value. T is of type int .

He throws out:

System.InvalidCastException: The specified listing is not valid.

It seems you cannot implicitly convert a string to int in C #, how can I fix this code so that it can handle the conversion of 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); } 
+4
source share
4 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 do).

+11
source

One possibility would be to use

 return (T)Convert.ChangeType(yourValue, typeof(T)); 

Note that this will throw an exception if yourValue not an instance of a type that implements IConvertible . It also throws an exception if the value itself cannot be converted, for example, if you have "abc" instead of "100".

+7
source

Use Convert.ChangeType .

 public static T InternalData<T>() { return (T)Convert.ChangeType("100", typeof (T)); } 

It still throws an error if the values ​​cannot be converted, but will not try to do a live broadcast. It can convert strings to ints ok.

+4
source

Do not confuse casting and converting! If the true type of expression is unknown to the compiler, for example. because it is printed as an object , and you know your own type, you can tell the C # compiler: "Hey, I know it a int , so please treat it as an int ."

  (int)expression 

In your case, the expression is a string expression that cannot be distinguished from int , just beacuase is not int . However, you can convert the string to int if it represents a real integer. In addition, the type of the result of your conversion is unknown, since it is common. Use (T)Convert.ChangeType(...) , as others have already pointed out.

+1
source

Source: https://habr.com/ru/post/1432480/


All Articles