I have an interface with the generic method:
interface IConverter
{
void Convert<T>(T value);
}
I would like to implement it for any type, but also I know that for string
the method logic can be simplified, so I'd like to overload it specifically for string
(like in this question):
class Converter : IConverter
{
public void Convert<T>(T value)
{
Console.WriteLine("Generic Method " + value);
}
public void Convert(string value)
{
Console.WriteLine("String Method " + value);
}
}
That works fine when I have instance of Converter
and call method directly. The code
var converter = new Converter();
converter.Convert("ABC");
converter.Convert(123);
outputs
String Method ABC
Generic Method 123
However, when I work with interface (like in any app with DI), I can't call my overload for string
. The code
var converter = (IConverter)new Converter();
converter.Convert("ABC");
converter.Convert(123);
outputs:
Generic Method ABC
Generic Method 123
Is there anyway to accomplish calling of string
overloaded method without type checking like
if (typeof(T) == typeof(string))
...
?