Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a method, into interface, with parameter and returned value generic in C#

I would like to implement a interface with generic input parameter and returned value in C#. At the moment I have defined a interface:

interface IResponseFormatter
{
    T formatResponseOptimizated<T>(T[] tagsValues);
}

after that I have tried to implement a concrete class:

public class FormatResponseInterpolatedData : IResponseFormatter

{
    ILog log = LogManager.GetLogger(typeof(HistorianPersistenceImpl));



    public Dictionary<string, List<object[]>> formatResponseOptimizated <Dictionary<string, List<object[]>>> (IHU_RETRIEVED_DATA_VALUES[] tagsValues)
    {
        log.Info("ENTER [formatResponseOptimizated] tagValues: " + tagsValues);
        Dictionary<string, List<object[]>> result = new Dictionary<string, List<object[]>>();

        // built data logic

        return result;
    }
}

I would like to understand what I'm wrong about and how I can to make this implementation type.

like image 988
Stefano Avatar asked Jan 21 '26 02:01

Stefano


1 Answers

You are defining a generic method in a non-generic interface.

Move T from being formatResponseOptimizated type parameter to IResponseFormatter type parameter, and provide a specification in the implementing class:

interface IResponseFormatter<T> {
    // Follow C# naming conventions: method names start in an upper case letter
    T FormatResponseOptimizated(T[] tagsValues);
}
public class FormatResponseInterpolatedData
     : IResponseFormatter<Dictionary<string,List<object[]>>> {
    public Dictionary<string,List<object[]>> FormatResponseOptimizated(Dictionary<string,List<object[]>>[] tagsValues) {
        ...
    }
}

Note that with a single type parameter T the return type of FormatResponseOptimizated must match the type of array element that it takes as its parameter T[]. If the two should be different, parameterize your interface on two types, say, TArg for the argument and TRet for return.

like image 150
Sergey Kalinichenko Avatar answered Jan 22 '26 16:01

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!