daxu
daxu

Reputation: 4074

generic method with multiple type parameters in c#

Thought I was doing something simple, but somehow can't make it even compile.

protected List<R> Retrieve<R>(T request)

I want to write a generic method that can return different responses base on the request type. So when I call a web api site, I may get different strong typed requests, but in this function, I will do the json serialization, send the request, and deserialization the response back.

Looks like c# won't allow me to do this. Is there any workaround or I will need to write different methods for each request.

Upvotes: 0

Views: 305

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112352

Since you are using two different type parameters, you must define two of them

protected List<R> Retrieve<T, R>(T request)

Note that one or both of them could be declared at the type (class/struct) level.

class C<T>
{
    protected List<R> Retrieve<R>(T request)
    {
        return default;
    }
}

or

class C<R>
{
    protected List<R> Retrieve<T>(T request)
    {
        return default;
    }
}

or

class C<T, R>
{
    protected List<R> Retrieve(T request)
    {
        return default;
    }
}

This is comparable to the Func<T,TResult> Delegate which is declared like this

public delegate TResult Func<in T,out TResult>(T arg);

Upvotes: 5

andyb952
andyb952

Reputation: 2008

The only way I can see this being possible to is to use constraints like so:

// This is to constrain T in your method and call ToRType()
public interface IConvertableToTReturn
{
    object ToRType(object input);
}

protected List<TReturn> DoSomethingAwesome<T, TReturn>(T thing)
    where T : IConvertableToTReturn
{
    // Do what you need to do. (Return with thing.ToRType())
}

Upvotes: 0

Related Questions