Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting a string to a generic

I have this method:

public T GetInput<T>()
{
     T result;

     if( (typeof)T == Type.GetType("string"))
     {
           result = GetStringInput(); // returns a string
     }

      // Etc for a bunch of different types
}

The error I'm getting is that I can't implicitly cast a string to a "T". The point of the function is to be able to get input of any specified type and make sure to do type validation on the input before returning it. Ideas?

like image 367
ARW Avatar asked Mar 17 '26 09:03

ARW


1 Answers

You cannot simply assign variable of undetermined on compile time type T with string event if you are certain that it is correct code. Compiler will not allow it. To force this you can do this:

result = (T)(object)GetStringInput();

this dual cast will explicitly say to compiler that you take responsibility for this line.

like image 77
Rafal Avatar answered Mar 18 '26 23:03

Rafal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!