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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With