Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do nested generics in C# mean?

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

like image 845
Scott Davies Avatar asked Aug 10 '10 03:08

Scott Davies


People also ask

What are generics in C?

Generics are similar to templates in C++ but are different in implementation and capabilities. Generics introduces the concept of type parameters, because of which it is possible to create methods and classes that defers the framing of data type until the class or method is declared and is instantiated by client code.

What are the benefits of using generics in C#?

Generics shift the burden of type safety from you to the compiler. There is no need to write code to test for the correct data type because it is enforced at compile time. The need for type casting and the possibility of run-time errors are reduced. Better performance.

Do generics increase performance?

With using generics, your code will become reusable, type safe (and strongly-typed) and will have a better performance at run-time since, when used properly, there will be zero cost for type casting or boxing/unboxing which in result will not introduce type conversion errors at runtime.


1 Answers

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.

like image 58
Rex M Avatar answered Sep 30 '22 14:09

Rex M