Generic Methods
A generic method is a helper that works with many kinds of things, like a scoop that can lift sand or snow. You write it once, and it adapts to whatever type you give it.
In this page:
Syntax
static ReturnType MethodName<T>(T parameter)
{
// body
}
MethodName<type>(argument); // type can often be inferred: MethodName(argument);
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using operators like
a + bora > bon a value of typeT, which does not compile because an unconstrainedTcould be any type; add a constraint or useIComparable<T>. - Calling a generic method like
Create<T>()without specifying<int>, when the compiler cannot inferTbecause no argument uses it. - Writing
new T()inside a generic method withoutwhere T : new(), which is a compile error.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: