Demystifying C# Generics

AramT
88.9K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

So in our first example we will be converting a method that has objects defined as its input parameters to a generic method, the exercise at the end of this page will give you hands-on experience for how to convert a normal method to a generic method.

In C#, to make your method generic, first you need to add the <T> after the end of the method name and before the opening parenthesis of the method.

Now to call the generic method, you will do the normal method call specifying the 2 arguments, the JIT (just-in-time) compiler will tell the type of the passed arguments and will deal with them naturally as if you are passing the concrete types.

let’s take a look at the following example method, that accepts 2 parameters of type object and compares the value of the 2 objects.

Now this might serve well in terms of code reusability while not having to the boxing/unboxing feature with object types. However, you will risk getting runtime errors due to unsafe casting and there will be cost for boxing/unboxing.

Can you rewrite the below method Compare to become a generic method?

The above method is the simplest implementation for generics method. I just wanted you to understand the structure of method when it has the parameter T.

In the next part, we will be writing a generic class.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content