CodeBlanks Logo Icon CodeBlanks

Generic class

C# course · Intermediate · Lesson 70/116

Learn to define a generic class with <T>.

What is a generic class?

A generic class is declared with a type parameter. The letter T is the most common parameter name; it is a placeholder type. The declaration class Box<T> says that Box can work with any type.

When you use it, you supply a concrete type: Box<int> is an integer box, Box<string> is a string box. The compiler produces a separate type per instantiation, so type safety is preserved and boxing is avoided. Generic classes reduce code duplication while keeping safety.

Same class, different types

After defining a generic class you can instantiate it with any type. Box<int> and Box<string> are instances of the same template but with different types.

The inner T Value property changes with the concrete type: int Value in Box<int>, string Value in Box<string>. The compiler catches wrong assignments at compile time. A non-generic solution would lose this safety.

Exercise Define the Box<T> class

Define a generic Box<T> class with a public T Value { get; set; } property. In Main create a Box<int> and a Box<string>; assign 42 and "Hello" to their Values. Print each Value with Console.WriteLine.

Show example solution
Write class Box<T> { public T Value { get; set; } }. In Main add var intBox = new Box<int> { Value = 42 }; var strBox = new Box<string> { Value = "Hello" }; Console.WriteLine(intBox.Value); Console.WriteLine(strBox.Value);
Example solution:
using System;

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

class Program
{
    static void Main()
    {
        var intBox = new Box<int> { Value = 42 };
        var strBox = new Box<string> { Value = "Hello" };
        Console.WriteLine(intBox.Value);
        Console.WriteLine(strBox.Value);
    }
}

Test yourself

  1. How is a Box<T> class declared?

    • class Box<T> { }
    • class Box<T> T { }
    • class Box(T) { }
    • class Box : T { }
    Show answer

    class Box<T> { } — Correct. The type parameter goes in angle brackets after the class name.

  2. The type parameter letter

    class Box<____> { public T Value { get; set; } }
    Show answer
    class Box<T> { public T Value { get; set; } }
  3. Match each generic piece to its meaning

    <T>
    Type parameter
    Box<int>
    Concrete instance
    T Value
    Type-parameter property
    new Box<T>()
    Instance creation

All lessons in Intermediate