Search code examples
c#virtualoverloadingstatic-members

How can I have a kind of virtual static member in c#


I have a class like:

public class Food
{
  public static IList<Ingredient> ingredients
  public bool uses(Ingredient i)
  {
    return ingredients.Contains(i);
  }
}

Then I inherit from it to make various kinds of food like:

public class Cake : public Food
{
  public static IList<Ingredient> ingredients = new List<Ingredient>()
  {
    Sugar,
    Eggs,
    Milk
  }
}

Now I want to be able to do

Food f = getFood();
if (f.uses(Eggs))
{
   // Do something
}

So I want to have a static list of ingredients that (for example) all cakes can share, rather than a list per instance of Cake and be able to access it in a virtual way.

I'm willing to stir the code around to get a similar effect if needed!


Solution

  • In such cases, the OOD "prefer" to make the class Food abstract, since the "Ingredients" will be different from a Food to another. Thus, as others have pointed out, making this list static is meaningless, since static should be a modifier to an attribute which is not differentiating by the objects.

    I suggest a solution as follows:

    public abstract class Food
    {
       public abstract IList<Ingredient> Ingredients
       {
           get;
       }
    }
    

    Now any class - to be a concrete - will be driven from Food and therefore it must implement this property so that it gives its own ingredients:

    public class Cake : Food
    {
      public override IList<Ingredient> Ingredients
      {
          get { 
                  return new IList<Ingredient>()
                  { Sugar, Eggs, Milk };
              }
      }
    }