C# Generic Methods
A generic method is a method with a type parameter. One written method then works for many types.
Swapping two ints
Swap takes two values of one type. It exchanges them through a temporary variable.
using System;
class Program
{
static void Swap<T>(T a, T b)
{
T temp = a;
a = b;
b = temp;
Console.WriteLine(a);
Console.WriteLine(b);
}
static void Main(string[] args)
{
Swap<int>(4, 9);
}
}The same method with strings
The same Swap body runs with strings. Only the type in the call changes.
using System;
class Program
{
static void Swap<T>(T a, T b)
{
T temp = a;
a = b;
b = temp;
Console.WriteLine(a);
Console.WriteLine(b);
}
static void Main(string[] args)
{
Swap<string>("apple", "pear");
}
}The first element of an array
First reads element zero of any array. The return type is the type parameter itself.
using System;
class Program
{
static T First<T>(T[] items)
{
return items[0];
}
static void Main(string[] args)
{
int[] numbers = { 5, 8, 2 };
string[] words = { "cat", "dog" };
Console.WriteLine(First<int>(numbers));
Console.WriteLine(First<string>(words));
}
}Example
using System;
class Program
{
static T Middle<T>(T[] items)
{
return items[items.Length / 2];
}
static void Main(string[] args)
{
int[] scores = { 3, 6, 9 };
string[] colors = { "red", "green", "blue" };
Console.WriteLine(Middle<int>(scores));
Console.WriteLine(Middle<string>(colors));
}
}Key points
- The type parameter sits in angle brackets after the method name.
- A call fills in the type from the arguments.
- The same body runs for every type.
- The compiler checks each call against the real type.
- A generic method can sit inside a plain class.
In this example, Middle returns the element at the middle index of an array. The int call returns 6. The string call returns green. One body serves both arrays.
Note
Generic methods remove the need for one copy of a method per type.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the T in Swap<T> stand for?