1

I have a such code:

class A<T>
{
}

class B : A<int>
{
}
    
class C<T1, T2>
  where T1 : A<T2>
{
}

But when I want to instantiate the C class with B as first generic type I need to specify second type too.

Can I somehow ask C# to infer the T2 by itself?

  • 2
    Type inference does not consider generic constraints, and there is no partial type inference. See also [Why must I provide explicitly generic parameter types While the compiler should infer the type?](https://stackoverflow.com/questions/4477636/why-must-i-provide-explicitly-generic-parameter-types-while-the-compiler-should) – JonasH Aug 19 '21 at 09:27
  • No, the choices are you supply no generic type parameters and type inference applies or you provide all type parameters. – Damien_The_Unbeliever Aug 19 '21 at 10:37

1 Answers1

0

inference happens when the compiler can infer the type from the context

public void DoSomething<T1,T2>(T1 key,T2 value)
{
...
}

when called as

string a;
int b;
DoSomething(a,b); 

this will work because a & b's types are defined in the context of the call so T1 has to be a string and T2 has to be an int because that is what a and b are

in your example

class A<T>
{
}

class B<T1, T2>
  where T1 : A<T2>
{
}

when called as

var b = new B();

what is T1? what is T2? the compiler has no idea

and even if you did

var b = new B<A<string>>();

your where clause says that A has to implement A but what is T unless you specify it the compiler has no clue? maybe T2 is an int and in which A<string> clearly fails the where clause and a error needs to be thrown

if you defined your B class as

class B<T1, T2>:A<T2>
{
}

then the compiler will know that whatever T2 is, is passed to A

Edit: if all you care about is that the T1 is an example of A and you don't care what the type is use an interface

interface IA{
}
class A<T>:IA
{
}
class B<T>:
    where T:IA
{
}
MikeT
  • 5,398
  • 3
  • 27
  • 43
  • I think that you understood my question not right, I have changed it, can you please check it again? – Zakhar Kurasov Aug 19 '21 at 10:27
  • its the same issue a where clause isn't a type directive its a check to see if you have passed in a valid value so you are saying that T1 one can be any class that is based upon a class using A what is that something? with out specifying T2 that is not known, if you want to ifer it you need to remove the where clause and make a concrete assertion of that the type is – MikeT Aug 20 '21 at 09:26
  • think of it like going to the shop you have been asked to pick up something to drink but the person doesn't want alcohol, you you pick up a bottle of vodka, so is that something to drink yes does it contain alcohol yes so its not suitable so your where is not alcohol ensure you pick up the right product, however if you had been left to infer this with out being told that you didn't want alcohol how would you know the vodka was the wrong item to buy? – MikeT Aug 20 '21 at 09:42