Quick Tour Of Generics In C#
Generics have been around since C# 2.0 and has become a tool we leverage so naturally now in C# we almost don’t even think about it. So let’s change that…
Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code.
Essentially generics allow you parameterize types and methods. Just as normal methods have parameters to tell them what values to use, generic types and methods have type parameters to tell them what types to use.
Type parameters are placeholders for a type.
There are constructed types and generic types. A constructed type is when the type arguments are specified. For example,
A generic type is when the type arguments are not specified. For example,
As per the code snippet below, writing a method to swap two Integer values is pretty rudimentary. But what if later we needed to do the very same but with Strings. This would result in two methods, or perhaps overloads.
Generics to the rescue. We’ve isolated the type as a form of abstraction (
T) to act as a placeholder for the type we intend to use.
When the method is actually called, that placeholder is replaced with the type of the values used.
The value of Generics here is that it grants you productivity improvements, expressiveness and moves some safety concerns from execution time to compile time.
Note the two ways in which the method can be called. One with the type explicit, and the other implicit through type inference. The compiler is inferring the type parameters based on the method arguments you pass.
A generic is simply a placeholder for a type.