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

Generic Methods

In this page:

  1. Generic Methods

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);
    }
}
🔒

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.