I have a base class like this:
class FooBase
{
public bool Do(int p) { /* Return stuff. */ }
}
And a child class like this:
class Foo<T> : FooBase
{
private Dictionary<T, int> Dictionary;
public bool Do(T p)
{
int param;
if (!Dictionary.TryGetValue(p, out param))
return false;
return base.Do(param);
}
}
If the user creates a Foo<string>
object called "fooString", then he can call both fooString.Do(5)
and fooString.Do("test")
but if he creates a Foo<int>
object called "fooInt", he can only call the Do method of the derived class. I prefer the second no matter what the T
is.
The Do methods in both of these classes essentially do the same thing. The one in the derived class gets an integer from a Dictionary<T, int>
using the given parameter and calls the Do method of the base class using it.
That's why I want to hide the Do method of the FooBase
in Foo<T>
. How can I achieve this or something similar? Any design advice to overcome this would also be nice.
No, that's not true. If the declared type of the variable is
FooBase
, it will still call theFooBase
method. You're not really preventing access toFooBase.Do
- you're just hiding it.Full sample code to show that:
You need to think about Liskov's Substitutability Principle.
Either
Foo<T>
shouldn't derive fromFooBase
(use composition instead of inheritance) orFooBase.Do
shouldn't be visible (e.g. make it protected).