gr8gonzo
asked on
C# Extending Classes and Overriding Types
I have a scenario where I am working with a 3rd party library that I cannot change, and I'm trying to figure out a way to work with some of their types. Basically, they have the following classes:
I'm working on a "helper" class that removes seeds, so I'm trying to do something like this:
Also, if I try to use any valid type like "Cherry" instead of "Food" in the parent class in order to make the RemoveSeeds work, then I'm forced to override / hide the "item" in the child classes and the parent methods don't even see the right "item".
I've experimented with trying to use dynamic <T> types in my class definitions, but with no luck. Can anyone point me in the right direction here?
public class Food
{
... properties that apply to all food ...
}
public class Pie : Food
public class Grapefruit : Food
{
public int NumberOfSeeds = 50;
}
public class Cherry : Food
{
public int NumberOfSeeds = 1;
}
Now, "Grapefruit" and "Cherry" both have the "NumberOfSeeds" property, but that property is not part of the Food class.I'm working on a "helper" class that removes seeds, so I'm trying to do something like this:
public class FoodHelper
{
public Food item;
public void RemoveSeeds()
{
item.NumberOfSeeds = 0;
}
}
public class GrapefruitHelper : FoodHelper
{
new public Grapefruit item;
}
public class CherryHelper : FoodHelper
{
new public Cherry item;
}
I'm trying to avoid having to redefine "RemoveSeeds" over and over again in the child classes (the real method is pretty monstrous), but when I define it in the parent class, I get a warning that "Food" doesn't contain the "NumberOfSeeds" property, which is correct.Also, if I try to use any valid type like "Cherry" instead of "Food" in the parent class in order to make the RemoveSeeds work, then I'm forced to override / hide the "item" in the child classes and the parent methods don't even see the right "item".
I've experimented with trying to use dynamic <T> types in my class definitions, but with no luck. Can anyone point me in the right direction here?
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Gave all the points to kaufmed for the help, but the ultimate answer here was a different approach to the code.
ASKER
I was hoping to avoid Reflection for the performance hits you mentioned. Is there a way to define a -new- type "group" like "Fruit" that tells .NET that "This parameter called Fruit will always be either Cherry or Grapefruit?"