CodeBlanks Logo Icon CodeBlanks

Generic methods

C# course · Intermediate · Lesson 71/116

Learn to define generic methods and call them with type arguments.

Generic methods

Not only classes but also methods can be generic. A generic method carries its own type parameter in its signature. The declaration void Swap<T>(ref T a, ref T b) says the Swap method can be called with any type.

At the call site you can state the type explicitly: Swap<int>(ref x, ref y). Or you can let the compiler infer it from the arguments: Swap(ref x, ref y). This is called type inference. Generic methods avoid duplication without writing a separate version per type.

Pass by reference with ref

In the Swap example the ref keyword makes the parameter pass by reference. Changes inside the method are visible to the caller. With default pass-by-value those changes would be lost.

Generic methods support ref T syntax. The call must also include ref: Swap(ref x, ref y). This makes pass-by-reference explicit on both the definition and the call side. Accidental pass-by-value is prevented.

Exercise Write the Swap<T> method

Add a static void Swap<T>(ref T a, ref T b) method to the Program class. In the body swap with T temp = a; a = b; b = temp;. In Main define int x = 1, y = 2;; call Swap<int>(ref x, ref y); print x and y with Console.WriteLine.

Show example solution
Write static void Swap<T>(ref T a, ref T b) { T temp = a; a = b; b = temp; }. In Main add int x = 1, y = 2; Swap<int>(ref x, ref y); Console.WriteLine(x); Console.WriteLine(y);
Example solution:
using System;

class Program
{
    static void Swap<T>(ref T a, ref T b)
    {
        T temp = a;
        a = b;
        b = temp;
    }

    static void Main()
    {
        int x = 1, y = 2;
        Swap<int>(ref x, ref y);
        Console.WriteLine(x);
        Console.WriteLine(y);
    }
}

Test yourself

  1. The generic method parameter

    static void Swap<____>(ref T a, ref T b) { }
    Show answer
    static void Swap<T>(ref T a, ref T b) { }
  2. What happens after Swap<int>(ref x, ref y)?

    int x = 1, y = 2;
    Swap<int>(ref x, ref y);
    • x=1, y=2 (unchanged)
    • x=2, y=1 (swapped)
    • Compile error
    • Runtime error
    Show answer

    x=2, y=1 (swapped) — Correct. ref-passed values change inside the method.

  3. Match each generic method piece

    <T>
    Method type parameter
    ref
    Pass by reference
    Swap<int>(...)
    Explicit type call
    Swap(...)
    Inferred type call

All lessons in Intermediate