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

Generic Classes

In this page:

  1. Generic Classes

Generic Classes

A generic class uses a type parameter, like Box<T>, so the same class definition can work with any type while staying fully type-safe. The actual type is supplied when the class is instantiated, such as Box<int> or Box<string>. This avoids duplicating the same class for every type you need it to hold.

Note: Generic type parameters are conventionally named T, or something descriptive like TKey/TValue for multiple parameters.

Example: Generic Classes

markup
using System;

class Box<T>
{
    private T value;

    public void Set(T value)
    {
        this.value = value;
    }

    public T Get()
    {
        return value;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Box<int> intBox = new Box<int>();
        intBox.Set(42);
        Console.WriteLine(intBox.Get());

        Box<string> strBox = new Box<string>();
        strBox.Set("hello");
        Console.WriteLine(strBox.Get());
    }
}
🔒

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.