C# Generics: Creating Reusable and Type-Safe Code

Learn about generics in C# and how they enable creating reusable and type-safe code that works with different data types without code duplication. This tutorial explains generic classes, methods, type parameters, constraints, and how generics enhance code maintainability and efficiency.



Understanding Generics in C#

What are Generics?

Generics in C# allow you to write classes and methods that can work with different data types without needing to create separate versions for each type. Think of it as using a placeholder for a data type; the actual type is specified when the generic class or method is used. Generics improve code reusability and type safety, reducing code duplication and enhancing maintainability.

Generic Classes

To create a generic class, you use angle brackets (`<>`) to specify a type parameter. This type parameter acts as a placeholder that will be replaced with a concrete type when an instance of the class is created. The type parameter is typically represented by a capital letter (e.g., T, U, V) and should be a descriptive name that indicates the purpose of the parameter.

Example C# Code (Generic Class)

public class MyGenericClass<T> {
    private T _data;
    public MyGenericClass(T data) { _data = data; }
    public T GetData() { return _data; }
}

This creates a generic class `MyGenericClass` that can work with any data type.

Generic Methods

Similarly, you can create generic methods. The type parameter is specified in the method signature.

Example C# Code (Generic Method)

public void ShowData<T>(T data) {
    Console.WriteLine(data);
}

This creates a generic method `ShowData` that can accept and display any data type.

Examples: Using Generic Classes and Methods

These examples demonstrate creating and using generic classes and methods. Note that the compiler automatically infers the types from the arguments you provide.

C# Code

public class Example {
    public static void Main(string[] args) {
        MyGenericClass<string> strGeneric = new MyGenericClass<string>("Hello");
        MyGenericClass<int> intGeneric = new MyGenericClass<int>(123);
        // ... (Call to generic method) ...
    }
}

Conclusion

Generics in C# are a powerful tool for writing reusable and type-safe code. They significantly improve code efficiency and reduce the need for writing multiple versions of the same code for different data types.