Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generics with concrete implementation

Tags:

c#

generics

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
}
like image 364
Sebastian Widz Avatar asked Mar 11 '23 22:03

Sebastian Widz


1 Answers

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)
{
}
like image 175
Reed Copsey Avatar answered Mar 25 '23 04:03

Reed Copsey