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

Generic Classes

A generic class is a container that can hold any type you choose, like a box labeled 'for shoes' or 'for toys'. You write it once and use it with many types safely.

In this page:

  1. Generic Classes
Syntax
csharp
class ClassName<T>
{
    private T value;
    public void Set(T value) { this.value = value; }
    public T Get() { return value; }
}

ClassName<type> variable = new ClassName<type>();

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());
    }
}
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. Forgetting the type argument, such as Box b = new Box(); for Box<T>, which is a compile error.
  2. Assuming T supports operators such as + without a constraint, which is a compile error.
  3. Using new T() without the new() constraint.
🔒

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.