C# unbounded generic type as constrain

1.8k views Asked by At

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.

3

There are 3 answers

3
Lee On BEST ANSWER

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

public T DoSomething<T, TKey, TValue>(T dictionary) where T : IDictionary<TKey, TValue> { ... }
0
Alex Zhukovskiy On

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.

0
Jeppe Stig Nielsen On

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

public IDictionary<TKey, TValue> DoSomething<TKey, TValue>(IDictionary<TKey, TValue> dictionary)
{
...
}