Member-only story
Discovering generics in C#
Because abstraction can save you lots of code repetitions!
As a dev, there is quite a common issue you may have to deal with when working on a growing project: code snippets that keep repeating over and over again here and there in the codebase. This happens quite often, because factorising code is hard and requires quite a lot of discipline.
But in C#, there’s actually a great tool for defining data type-specific behaviour in a consistent and efficient way: C# generics.
So, in this tutorial, let’s have a quick look at this cool feature and see how it can help us sanitise our codebase :)
Understanding the basics
When you define a generic method or class, you essentially define an empty model, a blueprint than can then be instantiated and that doesn’t know (or knows only partially) what data type it is working on. From a programmer’s point of view, the unknown data type(s) are labelled and booked in memory, just like a variable: