Generic Methods
Type parameters on methods.
What Are Generic Methods?
A generic method declares one or more type parameters of its own, written in angle brackets after the method name. The same method body then works for many types without casting or duplication.
Type parameters are placeholders like T. The compiler substitutes the real type at the call site, keeping everything strongly typed.
void Print<T>(T value)
{
Console.WriteLine(value);
}Declaring a Type Parameter
The type parameter list <T> sits between the method name and the parameter list. You can use T as a parameter type, a return type, or a local variable type inside the body.
By convention single type parameters are named T; descriptive names like TKey are also common.
T Echo<T>(T input)
{
return input;
}All lessons in this course
- Generic Methods
- Generic Classes
- where Constraints
- Generic Interfaces