You cannot convert to Tbecause T is not known at compile time. If you want your code to work, you can change the return type to ICarand remove the common return type T.
You can also use T. That will work too. If you use only the default constructor, you can also point to new()and use new T()to make your code work.
Examples
public ICar GetCar<T>()
where T : ICar
{
ICar objCar = null;
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;
}
Cast:
public T GetCar<T>()
where T : ICar
{
Object objCar = null;
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 (T)objCar;
}
New restriction:
public T GetCar<T>()
where T : ICar, new()
{
return new T();
}