I’ve got the following code:
public static T GetCar<T>() where T : ICar
{
T objCar = default(T);
if (typeof(T) == typeof(SmallCar)) {
objCar = new SmallCar("");
} else if (typeof(T) == typeof(MediumCar)) {
objCar = new MediumCar("");
} else if (typeof(T) == typeof(BigCar)) {
objCar = new BigCar("");
}
return objCar;
}
And this is the error I am getting: Cannot implicitly convert type 'Test.Cars' to 'T'
What Am I missing here? All car types implement the ICar interface.
Thanks
You cannot convert to
Tbecause of the fact that T isn’t known at compile time.If you want to get your code to work you can change the return type to
ICarand remove the genericTreturn type.You also can cast to
T. This would work too.If you only using the default constructor you can also constain on
new()and usenew T()to get your code to work.Samples
Cast:
New-constraint: