Generic is a silent hero in C # .NET (Folk knew as hiding hero). Generic 1 in “5 superhero brothers” constitutes LINQ (the remaining 4 are: Extension method, Delegate, Lambda Expression and yield). He hides in 50% of the code we write, so much so that we unconsciously use it, not knowing his existence or his name.

Photo by NESA by Makers on Unsplash

I wrote this article to honour the “silent hero” Generic, as well as guide you on how to create and use generic classes and generic methods.

The birth of Generic

Many of us use generic without knowing that it is generic. For example, when we want to create a list of students, we often write:

Yes, you will ask: Oh, this code is normal, do you see the hero hiding Generics? Yes, Generics hides inside those curly braces <>.

To make it easy to understand, let’s go back to .NET 1.0 when generics didn’t exist:

Without generics, the compiler cannot check errors at compiler time. Therefore, inline 2, we can add a Car object and a list of Student objects. When removing an element, we also have to cast it, because the compiler only understands it is an object. For these reasons, generic has been added in .NET 2.0. Effects of generic:

  • Help reuse the code. For example, We just need to write class List <T>, There can be any class.
  • Support compiler catch errors during compiler (Limiting the situation as line 2).
  • No more casting from the object.

Use Generic

Generic is applied in many classes List, Dictionary and LINQ, … When should we use LINQ? When we need to write a function that is reusable for many data types.

Sounds a bit confusing, isn’t it? Suppose I want you to write a swap function for 2 variables, can be used for types int, double, bool, including the class, how will you write?

Without generic

With the power of Generic, we only need to write 1 and only 1 method as follows:

Using the generic is as follows:

You can test the code here: Dotnet fiddle allows you to write and run C # code online, without any installation.

One more example, I just met in the process of code, it is used to get a random value in the list. We write a generic and use method (This method can be used with type int, double, … both Student or object, …).

Improved a bit by turning this method into an extension method for the List class:

You can try this code here:

As introduced at the beginning of the article, Generic is a pretty powerful tool, can save code time, as well as minimize many bugs in your code. If you want to learn more, you can read more here: See you in the following article.

Always be nice to anybody who has access to my toothbrush.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store