What do nested generics in C# mean?
Asked Answered
P

4

5

A bit of a basic question, but one that seems to stump me, nonetheless.

Given a "nested generic":

IEnumerable<KeyValuePair<TKey, TValue>>

Is this stating that IEnumerable can have generic types that are themselves KeyValuePair 's ?

Thanks,

Scott

Pollen answered 10/8, 2010 at 3:2 Comment(0)
H
6

Yes. The KeyValuePair type expects two generic type parameters. We can either populate them by pointing to concrete types:

IEnumerable<KeyValuePair<string, int>>

Or we can populate them by using other generic parameters already specified by the outer class:

class Dictionary<TKey, TValue> : IEnumerable<KeyValuePair<TKey, TValue>>

Generic type parameters are always specified "at-use", or at the point where you are using the class or method that requires them. And just like any other parameter, you can fill it with a constant, hard-coded value (or type in this case), or another variable.

Haematinic answered 10/8, 2010 at 3:5 Comment(1)
Thanks! As I said, always seems to stump me, but good to know I'm on the right path.Pollen
V
1

Yes, this is "An IEnumerable of Key/Value pairs." It would be declared thusly:

IEnumberable<KeyValuePair<string, string>> reallyComplicatedDictionary =
    new IEnumerable<KeyValuePair<string, string>>();

Or similar.

About the only think I can think this particular usage would do is allow you to have a "dictionary" with repeated keys.

Vestpocket answered 10/8, 2010 at 3:5 Comment(2)
Hmm, when did we become able to make new IEnumerables? ;)Lura
this is part of the Dictionary contract. The uniqueness is just enforced implicitly rather than explicitly.Haematinic
L
1

In a nut shell, it means that when you enumerate over that IEnumerable, you're going to get KeyValuePair<TKey, TValue> (for whatever types TKey and TValue are set to).

So, yes.

Lura answered 10/8, 2010 at 3:5 Comment(0)
C
0

Here

IEnumerable<KeyValuePair<string, int>>

The IEnumerable itself is not a generic. It knows that it is going to contain KeyValuePair. Here KeyValuePair is the generic which can contain any 2 generic types.

Chafer answered 10/8, 2010 at 3:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.