Search code examples
c#extension-methodsgeneric-type-argument

Can't omit the extension type argument when calling generic extension method with mutually constrained type parameters


public static class Utility {
  public static void ShadowDeserializeFile<T, S>(this T target, FileInfo file)
  where T : ShadowDeserializable<S> {
    S shadow = SomeHelpingMethod(file);
    target.ShadowDeserialize(shadow);
  }
}
public interface ShadowDeserializable<S> {
  void ShadowDeserialize(S shadow);
}

With above code I expect I can call it like:

var something = new SomeType(); //SomeType implements ShadowDeserializable<ShadowType>
something.ShadowDeserializeFile<ShadowType>(aFileInfoObj);

However Visual Studio issues error saying that using the generic method requires 2 type arguments. Only when calling as below it compiles:

something.ShadowDeserializeFile<SomeType,ShadowType>(aFileInfoObj);

I tried switching the order of type parameters in the method declaration, no difference.

How should I modify the declaration so that it could be called concisely as I expected?

Or is my expectation simply wrong as the extension type argument simply can't be omitted in this case?


Solution

  • There is no way to infer type of one parameter and specify another explicitly.You need to specify both types.Another option is to add a parameter of type S and then compiler will infer the second parameter's type for you based on what you pass to the method.Then you can call it without specifying any type. But if you don't need such parameter, specifying two types is the only option.

    If specifying one parameter where two type is expected would be possible, it would cause ambiguity.Imagine what would happen if you have another method with the same name that has one generic argument.