Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overload generic method from interface

Tags:

c#

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))
    ...

?

like image 249
kyrylomyr Avatar asked Jan 28 '26 14:01

kyrylomyr


2 Answers

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.

like image 78
Patrick Hofman Avatar answered Jan 31 '26 04:01

Patrick Hofman


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
}
like image 35
Rahul Avatar answered Jan 31 '26 04:01

Rahul