4

Is it possible in C# to create a generic method and add also a concrete implementation for given type? For example:

void Foo<T>(T value) { 
    //add generic implementation
}
void Foo<int>(int value) {
   //add implementation specific to int type
}
Sebastian Widz
  • 1,962
  • 4
  • 26
  • 45
  • I've dropped my answer and I've also voted to close because it's unclear what you're asking. It seems like an [XY problem](http://xyproblem.info/). – Matías Fidemraizer Jun 21 '16 at 21:38

1 Answers1

7

In your specific example you wouldn't need to do this. Instead, you'd just implement a non-generic overload, since the compiler will prefer using that to the generic version. The compile time type is used to dispatch the object:

void Foo<T>(T value) 
{ 
}

void Foo(int value) 
{
   // Will get preferred by the compiler when doing Foo(42)
}

However, in a general case, this doesn't always work. If you mix in inheritance or similar, you may get unexpected results. For example, if you had a Bar class that implemented IBar:

void Foo<T>(T value) {}
void Foo(Bar value) {}

And you called it via:

IBar b = new Bar();
Foo(b); // Calls Foo<T>, since the type is IBar, not Bar

You can work around this via dynamic dispatching:

public void Foo(dynamic value)
{
    // Dynamically dispatches to the right overload
    FooImpl(value);
}

private void FooImpl<T>(T value)
{
}
private void FooImpl(Bar value)
{
}
StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373