After having worked with dynamic languages for so long, I’ve really been enjoying the extra bit of structure that a statically typed language provides. Generics were something that I discovered earlier this week and I immediately liked the concept. The snippet of Python code below demonstrates a pretty common issue that I’ve experienced in the past. Typically, I’d have a collection objects that were assumed to be integers or some specific type. However, at some point an object that didn’t conform to my expectation gets added to the collection. Only later when I start to perform operations on the collection do I find out about this aberrant object.
list1 = []
list1.append(1)
list1.append(2)
list1.append("a")
total = 0
for element in list1:
# Including 'a' in list1 will cause a
# TypeError: unsupported operand type(s) for +=: 'int' and 'str'
total += element
print(total)
You could get around this by creating your own custom container class that did explicit type checking when elements were added to it, but it’s a nuisance to have to continually do this for each data type that you want to add to the container. Looking through the C# docs this approach seemed to be the prefered method for creating type safe containers prior to the addition of Generics.
Generics combine the best of both worlds: type safety + generalizability. With Generics the type of the contained objects is a parameter specified at instantiation of the containing class. This allows for general non type-specific implementations of the containing class, while still giving users the benefit of type safe containers.
The equivalent code below in C# generates a nice compiler error, not to mention my IDE (Rider) screams at me as well.
List<int> listOfInts = new List<int>();
listOfInts.Add(1);
listOfInts.Add(2);
listOfInts.Add("a");
int total = 0;
foreach (var element in listOfInts)
{
total += element;
}
Console.WriteLine(total);
Overall, I’m really enjoying exploring C# and learning about language features (like Generics) that I haven’t encountered before in the other languages that I’ve previously worked in.