Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing Generic Extension Method for Generic Type

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 
    }
}
like image 476
nevgeniev Avatar asked Nov 19 '11 16:11

nevgeniev


2 Answers

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.

like image 68
svick Avatar answered Oct 31 '22 00:10

svick


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.

like image 36
driis Avatar answered Oct 31 '22 00:10

driis