Suppose I have three methods:
void Foo(MemoryStream v) {Console.WriteLine (\"MemoryStream\");}
void Foo(Stream v) {Console.WriteLine (\"Stream\");}
void Fo
I had the same issue, and the unique solution I knew was try-casting it until I got something other than null
. Then, I would have the correct type at compile time and the compiler would know the right overload to call. I could not find another way to achieve this 'run-time polymorphism'.
To avoid using a dictionary or a switch-like solution (poor maintainability,as pointded out by Marc), just call Method((dynamic) o)
and DLR will call the correct overload method according to the run-time type.
Just remember to:
1) Provide a default overload with the most top type possible;
2) Watch out for any ambiguity during resolution of type at run-time (i.e. two indepenent interfaces and one implementation that uses both);
3) Handle null
case.
You can read more about it here.
Hope I've helped.