Tuesday, February 27, 2018

What are generics in C#?

Well, they showed up as of version two and they have distinct angle-bracket-flavored syntax with the type being extended getting wrapped in angle brackets while the type doing the extending is butted up against the left of the open angle bracket. Duh. I can remember answering this interview question by explaining that generics are all of the modern collections beyond the array and Hashtable of version one of C#, but that now seems like a really stupid answer. The KeyValuePair items in a Dictionary are not in and of themselves collections. The Dictionary is a collection, but not an individual KeyValuePair within it while KeyValuePair is a generic. A Tuple is not a collection. Well, I suppose it is a kind of collection. It's a boundary around a handful of dissimilar things. A Task in the async/await paradigm is not a collection. Maybe it is best to say that generics are a type that extends one or more types wherein the type(s) could generically be any type or could somewhat generically be the subset of types inheriting form a common parent (where T:Whatever). This is a different way to extend beyond inheritance tricks, partial classes, or extensions methods. Extension methods are methods that extend types not types that extend types. In typing up this blog post I found this old example of a Hashtable:

Hashtable hashtable = new Hashtable();
hashtable[1] = "One";
hashtable[2] = "Two";
hashtable[13] = "Thirteen";
foreach (DictionaryEntry entry in hashtable)
{
   Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
}

 
 

Yuck! I also ran into the ability to do a .Clear() on a Dictionary which will drop everything out of it and set the .Count back to zero. I can't recall using that before.

No comments:

Post a Comment