← Back to C# Course | Chapter 11: Generics | Lesson 2 of 6

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:

  1. Generic Methods
Syntax
csharp
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

markup
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);
    }
}
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
  1. Using operators like a + b or a > b on a value of type T, which does not compile because an unconstrained T could be any type; add a constraint or use IComparable<T>.
  2. Calling a generic method like Create<T>() without specifying <int>, when the compiler cannot infer T because no argument uses it.
  3. Writing new T() inside a generic method without where T : new(), which is a compile error.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.