Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic or generic approach is better? C#

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

  1. Do you see any advantages for the generic implementation compared to normal Driver? If yes, what are they?
  2. Which one do you prefer? A generic one or the normal one?
  3. Is there a better way to implement a generic driver?
  4. I am getting a feeling that generics in C# is very limited when compared with C++ templates. Is that true?

Any thoughts?

like image 977
Navaneeth K N Avatar asked Dec 18 '22 08:12

Navaneeth K N


1 Answers

  1. Absolutely no advantages in this case whatsoever. Except if you really want to create an instance of T in Drive(), which can be done without generics with delegate IVehicle VehicleBuilder();
  2. It depends on the situation. But generally speaking I'd prefer first.
  3. Again: it depends on what you want to do.
  4. Yes, this is true. Remember though, that C++ templates are compile-time (JIT time) constructs, whereas C# generics are run-time constructs.

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.

like image 152
Anton Gogolev Avatar answered Dec 31 '22 21:12

Anton Gogolev