Generics in C# (Part 2 - Creating Generic Methods)

seantwie03

Sean

Posted on April 7, 2019

Generics in C# (Part 2 - Creating Generic Methods)

Introduction

Part One of this series is a general overview of Generics that explored why they are used in Lists. This article will explain how to create your own Generic methods.

Concatenate Arrays of Any Type

I will demonstrate Generic methods by creating an extension method for System.Array. This extension method will combine two arrays, and since it is Generic it will work on any type of array; int[], string[], etc.

First let's look at how the method is called from Main().

Main

Since this is an extension method on System.Array, I create two arrays, then call Concatenate on the first array; passing the second array as an argument. I then repeat the same steps using a string array to prove the method will work on multiple types. In the second section I did not explicitly specify the Type parameter <string>, but the compiler can work it out, since the result is being assigned to a string[].

Now let's look at the Concatenate extension method.

ArrayExtension

First, I would like to point out the Type parameter after the method name. <T> signifies this is a generic method. You'll notice the return type and method parameters are also T. All these T's are replaced with whatever argument is passed into the Type parameter.

In the first code block in Main() I explicitly specify the type parameter, passing in <int>, so the compiler knows to replace all occurrences of T with int. In the second section of Main() I am assigning the result of Concatenate to a string[] so the compiler knows to replace all occurrences of T with string.

Continue to Part Three, where I will cover how to create Generic classes.

💖 💪 🙅 🚩
seantwie03
Sean

Posted on April 7, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related