If you are creating multiple methods with the same functionality but varies on the data type that they will accept or contribute on their functionality, then you can use generic methods to save you some typing. A general structure of a generic method is as follows:

returnType methodName<type> (type argument1)
{
    type someVariable;
}

You can see that a type was indicated after the method name, wrapped inside angle brackets. Now every occurrence of this type will be substituted by the type that was indicated inside these brackets. The program below shows an example of using a generic method.

using System;

namespace GenericMethodDemo
{
    public class Program
    {
        public static void Show<X>(X val) 
        {                                 
            Console.WriteLine(val);       
        }                                 

        public static void Main()
        {
            int intValue = 5;
            double doubleValue = 10.54;
            string stringValue = "Hello";
            bool boolValue = true;

            Show(intValue);    
            Show(doubleValue); 
            Show(stringValue); 
            Show(boolValue);   
        }
    }
}

Example 1 – Using a Generic Method

5
10.54
Hello
true

We created a generic method that can accept any kind of data and then show its value. We then pass different data to the same function. The method changes that type of X depending on the type of data passed as an argument. For example, when we passed an int value, all the occurrence of X in the method will be replaced by int so the method will look like this if an int value is passed.

public static void Show (int val)
{
    Console.WriteLine(val);
}

You can also explicitly indicate the type to be used by the generic method when you call that method (although it is not necessary). For example the calls to the method above can be rewritten like this:

Show<int>(intValue);
Show<double>(doubleValue);
Show<string>(stringValue);
Show<bool>(boolValue);

Note about using generic methods, we cannot include inside the code computations such as adding two numbers because the compiler cannot determine the actual type of the operands and if they can be properly added to each other. We simply show the values inside our method because the compiler can show any type of data using the Console.WriteLine() method.

public static void Show<X>(X val1, X val2)
{
    Console.WriteLine(val1 + val2); // ERROR
}

You can also specify multiple type specifiers for a generic method. Simply separate each type with a comma.

public static void Show<X, Y>(X val1, Y val2)
{
    Console.WriteLine(val1);
    Console.WriteLine(val2);
}

You can pass two different values to the method like this:

Show(5, true);

// OR

Show<int, bool>(5, true);

Therefore, X will be of type int and Y will be substituted with bool. You can also pass two arguments with the same type.

Show(5, 10);

// OR

Show<int, int>(5, 10);