0

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.

1
  • 1
    Try something like protected List<R> Retrieve<T, R>(T request) Commented Sep 2, 2019 at 14:53

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

2 Comments

you need to return default(List<R>);
No, since C# 7.1 you can use Default Literals. C# infers the type.
0

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())
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.