C# unbounded generic type as constrain
Asked Answered
G

3

6

Is it possible to have a generic constraint which is an unbounded generic type?

For example:

public T DoSomething<T>(T dictionary) where T : IDictionary<,>
{
    ...
}

Edit: Just to explain the context, I want to constrain the usage of the method to an IDictionary, but for the method itself it does not matter exactly what TKey and TValue are.

Gadget answered 1/8, 2012 at 18:4 Comment(2)
public V DoSomething<K,V>(IDictionary<K,V> dictionary) Is this what you meant?Silvio
Amir Abiri, why do you want the return type to be the same as the parameter type T? Are you going to return the parameter? There's probably no need for that. And you can't easily construct another T. Unless you want to constraint T : new() as well.Barrows
H
9

This isn't possible, you need to specify the type parameters:

public T DoSomething<T, TKey, TValue>(T dictionary) where T : IDictionary<TKey, TValue> { ... }
Hebe answered 1/8, 2012 at 18:8 Comment(3)
You see the funny thing is that TKey and TValue can be inferred from T and I don't need them anywhere in the body of the method. So I had hoped to make the generic signature cleaner.Gadget
@AmirAbiri - Could you constrain T to the non-generic IDictionary instead?Hebe
Well actually I used IDictionary only to simplify the example. My real type is "any subclass of BaseGameState<?>" (i.e T isn't an interface, it's my own base class).Gadget
B
1

No, you can't do that. Maybe you can use

public IDictionary<TKey, TValue> DoSomething<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
{
...
}
Barrows answered 1/8, 2012 at 18:10 Comment(0)
C
1

There is an issue in rosylin github, however, it's not done yet. So it's not possible right now, but I expect it will be relatively soon.

Cultivate answered 6/1, 2017 at 18:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.