Ziv Weissman Ziv Weissman - 3 months ago 15
C# Question

Abstract extension method inheritance from abstract class

I'm trying to achieve the following, not sure yet that it is at all possible:
(Behind the scene is a CarFactory I tried to do - implementing the Factory design pattern)

I have a abstract class "Car" with solid properties that are shared between all cars and I have features like "RadioDisc", "FuelInjection" which not all cars have.

There could be several types of "RadioDisc" or "FuelInjection".

Each of these features follows a certain pattern, has shared properties but the installation process on a car is different.

I want each feature to make changes to Car based on a method that can do some stuff.

The extension should look something like this:

Car myCar = new Car(); //Car is a class which has solid props & List of Feature class
FuelInjection V1 = new FuelInjection();
myCar.Install<FuelInjection>(V1) ;


Ideally it should do like this, but I have compiler error-


Extension method must be defined in a non-generic static class


Of course I don't want a general static method, I want a method that will have same signature but will do something diffrent to the car on each class that inherit Feature.

Example for feature is FuelInjection that add Cost to the car, and let's say improve FuelConsumption property on Car.

Abstract Feature class:

public abstract class Feature
{
internal float _cost;

public float Cost
{
get
{
return _cost;
}
}

public abstract void Install<T>(this Car car) where T : Feature;
}


Specific feature:

public class FuelInjection : Feature
{
public new void Install<T>(this Car car) where T : Feature
{
//In iDo some stuff to Car:
car.price += this._cost; //this suppose to be the Feature instance.
//I want to add the cost to property "Price" in Car.
}
}


Is that even possible in c#?
Is there a different direction to go maybe?

Answer

You can always define an interface(or use your abstract class):

public interface IFeature
{
    void Install(Car car);
}

inherit from it:

public class Feature : IFeature, IComparable
{
    public void Install(Car car) 
    {
         ....
    }
}

and then make an extension:

public static class CarExt
{
     public static void InstallFeature(this Car car, IFeature feature) 
     {
         feature.Install(car);  
     }
}

in case of your abstract class it would be just:

public static class CarExt
{
     public static void InstallFeature(this Car car, Feature feature) 
     {
         feature.Install(car);  
     }
}