C# Generics
Generics
In the Method Overloading chapter, you learned that many methods can have the same name, with different parameter types.
Look at these two methods. They do the same thing, but one takes an int and the other takes a string:
Example
static void Print(int value)
{
Console.WriteLine("Value: " + value);
}
static void Print(string value)
{
Console.WriteLine("Value: " + value);
}
If you also need the method for double and bool, you must write two more copies of the same code.
Generics solve this problem. With generics, you write the method only once, and the type is decided when you use the method.
Generic Methods
To create a generic method, write <T> after the method name. T is a type parameter: a placeholder for a type (T is short for "type").
Then use T as the type of the parameter:
Example
static void Print<T>(T value)
{
Console.WriteLine("Value: " + value);
}
static void Main(string[] args)
{
Print(25);
Print("Hello");
Print(true);
}
Example explained
- When you call
Print(25),Tbecomesint - When you call
Print("Hello"),Tbecomesstring - When you call
Print(true),Tbecomesbool
C# looks at the value you send and chooses the type for you. You can also write the type yourself: Print<int>(25).
You can use T more than once in the method. Here, T[] is an array of any type, and the loop goes through it:
Example
static void PrintAll<T>(T[] items)
{
foreach (T item in items)
{
Console.WriteLine(item);
}
}
static void Main(string[] args)
{
int[] numbers = {1, 2, 3};
string[] cars = {"Volvo", "BMW", "Ford"};
PrintAll(numbers);
PrintAll(cars);
}
Generic Classes
A class can also be generic. Write <T> after the class name, and use T inside the class.
This Box class can hold one value of any type:
Example
class Box<T>
{
public T content;
}
class Program
{
static void Main(string[] args)
{
Box<int> numberBox = new Box<int>();
numberBox.content = 42;
Box<string> textBox = new Box<string>();
textBox.content = "Hello";
Console.WriteLine(numberBox.content);
Console.WriteLine(textBox.content);
}
}
When you create an object, write the type inside < >:
- In
Box<int>,Tbecomesint, socontentis anint - In
Box<string>,Tbecomesstring, socontentis astring
C# still checks the type. If you try to put a string into a Box<int>, you get an error before the program runs.
Generics You Already Know
The List and Dictionary classes are generic classes. Their full names are List<T> and Dictionary<TKey, TValue>:
Example
List<string> cars = new List<string>(); // T is string
List<int> scores = new List<int>(); // T is int
Dictionary<string, int> ages = new Dictionary<string, int>(); // TKey is string, TValue is int
That is why one List class can hold strings, numbers, or objects of your own classes.
A Dictionary has two type parameters: TKey is the type of the keys, and TValue is the type of the values.