If you're implementing generic extension method for generic class is there a better way?
Because it would be natural to call func2 exactly as func1<V>()
rather than func2<T, V>()
i.e. to omit T parameter and call it like func2<V>()
public class A<T> where T : class {
public V func1<V>() {
//func1 has access to T and V types
}
}
public static class ExtA {
// to implement func1 as extension method 2 generic parameters required
// and we need to duplicate constraint on T
public static V func2<T, V>(this A<T> instance) where T : class {
// func2 has access to V & T
}
}
If func2()
had only the generic parameter T
, the compiler could infer it and you could call it without specifying the parameter.
But if you need both parameters, you have to specify them explicitly. Type inference is all or nothing: either it can infer all types used (and you don't have to specify them), or it can't and you have to specify all of them.
In your example, class A
does not know about V
, it only knows V
in the context of func1
. So func2 cannot magically infer V
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With