Nicolas Voron
Nicolas Voron

Reputation: 3006

C# function call with multiple generic types

I know that I can call a generic extension method

public static object Convert<U>(this U value) 

Like this (no <Class1> required):

Class1Instance.Convert()

But is there a way to call :

public static T Convert<U, T>(this U value) 
  where T : Class1, Interface1, new()
  where U : Class1, Interface2, new()
{
  /******/
}

With Class1Instance.Convert<Class2>() "only", instead of Class1Instance.Convert<Class1, Class2>()

Thanks,

EDIT :

Reformulation / simplification : Is there a way to have :

Result result = Convert<Result>(input); 

Where we know input of type Input, instead of having to say

Result result = Convert<Input, Result>(input)

With an extension method which looks like this :

static TResult Convert<TResult, TInput>(this TInput Input)

Upvotes: 3

Views: 2104

Answers (2)

Nicolas Voron
Nicolas Voron

Reputation: 3006

According to this post, generic parameter inference works only with input parameters. In my case, one of the generic parameter is a return type.

As it is required that generic types inference provides all of them, I have to specify each parameter explicitly.

Upvotes: 0

David Yaw
David Yaw

Reputation: 27864

There's no way to call Convert<U, T> by specifying Convert<Class2> in your calling code. However, if you really want the calling code to look like that, there is a possibility.

public static T Convert<T>(this Class1 value) 
  where T : Class1, IClass1, new()
{ ... }

Instead of being generic on the input type, just specify the parent class of the input type. This will give you the calling code you want, but it will make the method more complex. For example, if the conversion process involves creating a new U object (making use of the new() generic constraint in the old method definition), then you'll have to do it with reflection in the new method.

Upvotes: 2

Related Questions