I have a generic method:
public bool DoSomething<T>(T item) where T: IBase
{
return DoSomethingSpecific(item);
}
public bool DoSomethingSpecific(IBase item)
{
return true;
}
public bool DoSomethingSpecific(IAdvanced item)
{
return false;
}
Note that IAdvanced interface derives/inherits from IBase interface.
I have found that if I call DoSomething where the item is of type IAdvanced, it still always returns false. I don’t understand this. I know that since IAdvanced is a type IBase (as it is a child of this interface), it may cause confusion between the 2 overloaded types of the DoSomethingSpecific method. However, as I understand with my limited C# knowledge, the IAdvanced method should be chosen here. This is an example of how I made this conclusion:
public class Advanced: IAdvanced
{
public void CallMethod()
{
DoSomething(this);
}
}
This results in a true value.
However, if I do:
public class Advanced: IAdvanced
{
public void CallMethod()
{
DoSomethingSpecific(this);
}
}
It returns false, which is what I would expect.
I have to say that I have never used generics before. I have attempted though, but always get stuck on a case like this, and then completely fail to see the point of using generics (besides data structures such as trees and linked lists).
This time I decided to come here for some advice. Is there a clear problem with what I am trying to do? Does it perhaps not make sense to try and do what I am busy doing here?
As far as it knows, it’s an IBase. The compiler needs to deside which method are you calling and that’s why it’s choosing that one always.
A dirty trick will be to do this:
Another way is to use Double-Dispatch/Visitor pattern:
The DoSomething Method will be in your IBase interface:
And in your implementations:
In this case, the problem is solved using pure inheritance. The actual instance is the one that resolves which method to call. No ifs.