0
0
C Sharp (C#)programming~5 mins

Generic class declaration in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Generic classes let you create flexible blueprints that work with any type of data. This helps you reuse code without repeating it for each data type.

When you want a class to handle different types of data without rewriting it.
When building collections like lists or stacks that can store any type of item.
When creating utility classes that work with multiple data types safely.
When you want to avoid code duplication for similar classes that differ only by data type.
Syntax
C Sharp (C#)
class ClassName<T>
{
    // Members using T
}

T is a placeholder for any type you specify when using the class.

You can use any name instead of T, but T is a common convention.

Examples
A simple generic class Box that can hold any type of content.
C Sharp (C#)
class Box<T>
{
    public T Content;
}
A generic class with two type parameters to hold a pair of different types.
C Sharp (C#)
class Pair<T1, T2>
{
    public T1 First;
    public T2 Second;
}
A generic class with a constraint that T must be a reference type (class).
C Sharp (C#)
class Storage<T> where T : class
{
    public T Item;
}
Sample Program

This program creates a generic class Box that can hold any type. We make one box for integers and one for strings, then print their contents.

C Sharp (C#)
using System;

class Box<T>
{
    public T Content;

    public void ShowContent()
    {
        Console.WriteLine($"Content: {Content}");
    }
}

class Program
{
    static void Main()
    {
        Box<int> intBox = new Box<int>();
        intBox.Content = 123;
        intBox.ShowContent();

        Box<string> strBox = new Box<string>();
        strBox.Content = "Hello";
        strBox.ShowContent();
    }
}
OutputSuccess
Important Notes

Generic classes help avoid errors by checking types at compile time.

You can add constraints to limit what types can be used with your generic class.

Use descriptive names for type parameters if you have many, like TKey and TValue.

Summary

Generic classes let you write one class that works with any data type.

Use angle brackets <> to declare type parameters.

They improve code reuse and type safety.