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))
...
?
No. You cast converter to IConverter, so there is only one method visible on your converter variable: Convert<T>(T value).
You can overcome this by adding Convert(string) to the interface, or don't cast to the interface at all and keep using your Converter class. Only then the other method will be visible.
There are two ways,
Either you include that method in your interface like
interface IConverter
{
void Convert<T>(T value);
void Convert(string value);
}
Have that method specific to string created as extension method
public static void Convert(this string str, string value)
{
// code here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With