Introducing a generic extension method for a generic type

If you use a universal extension method for a universal class, is there a better way? Since it would be natural to call func2 exactly as func1<V>() , rather than func2<T, V>() , that is, omit the parameter T and name it as 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 } } 
+6
source share
2 answers

If func2() had only a common parameter T , the compiler could output it, and you could call it without specifying the parameter.

But if you need both parameters, you must specify them explicitly. Type input is all or nothing: either it can output all the types used (and you do not need to specify them), or it cannot, and you must specify all of them.

+4
source

In your example, class A does not know about V , it only knows V in the context of func1 . Therefore, func2 cannot magically infer V

+2
source

Source: https://habr.com/ru/post/901896/


All Articles