I can call Get
or Get
But when compiling I get:
Cannot implicitly convert typ
Actually, you can just convert it to object
and then to T
.
T var = (T)(object)42;
An example for bool
:
public class Program
{
public static T Foo()
{
if(typeof(T) == typeof(bool)) {
return (T)(object)true;
}
return default(T);
}
public static void Main()
{
bool boolValue = Foo(); // == true
string stringValue = Foo(); // == null
}
}
Sometimes, this behavior is desirable. For instance, when implementing or overriding a generic method from a base class or interface and you want to add some different functionalities based on the T
type.