Generic Methods
In this page:
Generic Methods
A method can be generic on its own, even inside a non-generic class, by declaring its own type parameter in angle brackets before the parameter list. The compiler usually infers the type argument from the arguments you pass, so you rarely need to specify it explicitly. This lets a single method work correctly across many types.
Note: You can call a generic method explicitly with Method<int>(...) if type inference can't figure it out.
Example: Generic Methods
using System;
class Program
{
static void PrintTwice<T>(T value)
{
Console.WriteLine(value);
Console.WriteLine(value);
}
static void Main(string[] args)
{
PrintTwice(5);
PrintTwice("hi");
PrintTwice(3.14);
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: