nevgeniev
nevgeniev

Reputation: 125

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 
    }
}

Upvotes: 6

Views: 1337

Answers (2)

svick
svick

Reputation: 244757

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.

Upvotes: 3

driis
driis

Reputation: 164281

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.

Upvotes: 2

Related Questions