Suppose I have three methods:
void Foo(MemoryStream v) {Console.WriteLine (\"MemoryStream\");}
void Foo(Stream v) {Console.WriteLine (\"Stream\");}
void Fo
This is not a "pretty" answer (indeed, since this is kinda subverting the intent of generics, it is hard to find a pretty answer inside the language), but you could perhaps code the overload lookups via a dictionary:
static readonly Dictionary> overloads
= new Dictionary> {
{typeof(Stream), o => Foo((Stream)o)},
{typeof(MemoryStream), o => Foo((MemoryStream)o)}
};
public static void Bar() {
Action
This isn't nice, and I don't recommend it.
For easier maintenance, you could perhaps move the overloads
population to a static constructor / type initalizer, and populate it via reflection. Note also that this only works for exact T
- it won't work if someone uses an unexpected type (Bar
for example) - although you could presumably loop over the base-types (but even then, it doesn't have great support for interfaces etc).
This approach doesn't have much to recommend it, all things considered. I would probably advise approaching the entire problem from a different angle (i.e. removing the need to do this).