Demystifying C# Generics
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
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.
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.