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