Generic methods

Like the Generic class, there can be generic methods, and a generic method does not necessarily have to be inside a generic class. A generic method can be inside a non-generic class as well. To create a generic method, you have to place the type parameter next to the method name and before the parenthesis. The general form is given here:

access-modifier return-type method-name<type-parameter>(params){ method-body }

Now, let's look at an example of a generic method:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Chapter7
{
class Hello
{
public static T Larger<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) > 0 ? a : b;
}
}

class Code_7_4
{
static void Main(string[] args)
{
int result = Hello.Larger<int>(3, 4);

double doubleResult = Hello.Larger<double>(4.3, 5.6);

Console.WriteLine("The Large value is " + result);
Console.WriteLine("The Double Large value is " + doubleResult);

Console.ReadKey();
}
}
}

The output of the preceding code is as follows:

Here, we can see that our Hello class is not a Generic class. However, the Larger method is a generic method. This method takes two parameters and compares them, returning the larger value. This method has also implemented a constraint, which is IComparable<T>. In the main method, we have called this generic method several times, once with int values and once with double values. In the output, we can see that the method was successfully able to compare and return the larger value.

In this example, we have used only one type of parameter, but it is possible to have more than one parameter in a generic method. We have also created a static method in this example code, but a generic method can be non-static as well. Being static/non-static doesn't have anything to do with a generic method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.163.161