0

I have a class of type Installer where TModel has a constraint. I want to create an extension method with the type signature :\

public static void DoRepetitiveStuff<TOtherObject, TModel>(this Installer<TModel> installer)
where TModel : class, IConstraint, new()
where TOtherObject : class, IOtherConstraint, new()
{
   installer.DoSomeStuff<TOtherObject>(c => { });
}

the goal being that eventually I can call the function using a simple installer.DoRepetitiveStuff<TOtherObject>();

For some reason when I call that function on my other file. It complains there isn't any extension method that accept a Installer in existance... I need to use it with:

installer.DoRepetitiveStuff<TOtherObject, TModel>();

Anyone knows why ?

  • 2
    You may introduce an intermediate class with generic method inside, to call it as `installer.GetExtension().DoRepetitiveStuff();`, as here: https://stackoverflow.com/questions/16479623/working-around-lack-of-partial-generic-type-inference-with-constraints/16479852#16479852 – Renat Feb 18 '20 at 17:21
  • 1
    You can either omit all or none of the generic parameters. It can only figure out one of the two therefore the none option isn't possible here and you have to explicitly write both. – Joelius Feb 18 '20 at 17:23

1 Answers1

2

The C# compiler can't infer a partial generic signature. It's basically all or nothing. Why?

Let's say your code is accepted, and then you create a new method:

public static void DoRepetitiveStuff<TOtherObject>(this Installer installer)
where TOtherObject : class, IOtherConstraint, new()
{
   installer.DoOtherStuff();
   installer.DoSomeStuff<TOtherObject>(c => { });
}

Now, which method does your code call? Yours or this one? We can't know, because it's ambiguous.

To avoid this, either the compiler infers the full signature, or none at all.

As an alternative, you would need to introduce another class that can do the inference for you. However, at this point, it's actually more concise to just specify both generic types.

Clay07g
  • 1,105
  • 7
  • 23
  • 1
    Ohhh I get it If you create a second signature with (Installer) it conflicts with my previous declaration if it didn’t include a “all or nothing for type inference” – Jean-Baptiste Zeller Feb 21 '20 at 22:14