I have two classes and an interface like
interface IVehicle
{
void Drive();
}
class Benz :IVehicle
{
public void Drive()
{
Console.WriteLine("WOW! driving benz");
}
}
class Ferrari : IVehicle
{
public void Drive()
{
Console.WriteLine("WOW! driving ferrari");
}
}
I got a Driver class which uses this.
class Driver
{
public void StartDriving(IVehicle vehicle)
{
vehicle.Drive();
}
}
There is one more driver which is generic.
class GenericDriver
{
public void StartDriving<T>() where T : IVehicle , new()
{
T vehicle = new T();
vehicle.Drive();
}
}
Questions
Any thoughts?
T
in Drive()
, which can be done without generics with delegate IVehicle VehicleBuilder();
Now on why would I want a generic Driver
. Consider:
class Driver<TVehicle>
where TVehicle : class, IVehicle, new()
{
public TVehicle Vehicle { get; set }
public Driver()
{
Vehicle = new TVehicle();
}
}
This way I'll be able to use a strongly-typed Driver<>.Vehicle
property which will be of a particular type, rather than of a more common IVehicle
.
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