C# Generics
Why do we need it?
Generic allows developers create classes or methods work with any data type.
Let’s take a look at the following example.
1 | //List.cs |
It’s a normal List class provides integer input and retrieval. How about we want the List class to provide input and retrieval with another data type? We need to create another class with another data type handle in traditional way.
1 | //StringList.cs |
Yes it works. But it always requires us to create new classes to process different data types, which will create a lot of code duplications. If there are any logic changes, we need to make code changes to all the places and it’s really unproductive. So the solution would be using a list of object.
1 | //ObjectList.cs |
But there’s another problem here is performance. If we use this class to store the primitive value types like integer, every time we insert a primitive value type into the list and it has to be boxed to be stored as an object. When we access the value, it has to be un-boxed and cause performance penalty. Or even we use reference types we want to cast an object like a book to an object or vice versa, it is casting again has performance penalty. So generics came as solution to resolve this problem. With generics we create a class once and reuse it multiple times without performance penalty.
How does it work?
1 | //GenericList.cs |
1 | //Program.cs --This is how we use generic type |
Now we don’t have performance penalty because our generic list is actually a list of integers/strings at runtime. It’s not a list of objects. No casting or boxing.
For most of the time we don’t need to create the generic list by ourselves. We will use the generic lists that are actually part of .net.
Constraints
1 | using System; |
The above example shows how to create a generic method inside a non generic class because we don’t always have to start with the generic class. We can also move the generic constraint to the class level as follow:
1 | using System; |