0Pricing
C# Academy · Lesson

Generic Classes

Reusable container types.

What Is a Generic Class?

A generic class declares one or more type parameters in angle brackets after the class name. Those parameters can be used for fields, properties, method signatures, and return types throughout the class.

This lets you write one container or service that works for many element types while staying strongly typed.

class Box<T>
{
    public T Value { get; set; }
}

Constructing a Generic Class

To create an instance you supply a concrete type argument. Box<int> and Box<string> are distinct constructed types.

Each constructed type behaves as if its T were replaced by the real type everywhere.

using System;

class Box<T> { public T Value { get; set; } }

class Program
{
    static void Main()
    {
        var b = new Box<int> { Value = 7 };
        Console.WriteLine(b.Value);
    }
}

All lessons in this course

  1. Generic Methods
  2. Generic Classes
  3. where Constraints
  4. Generic Interfaces
← Back to C# Academy