DEV Community

Saravanakumar R
Saravanakumar R

Posted on

Generics

Generics are a way to create reusable and flexible code by allowing you to define a class, method, or data structure without specifying the exact type it will work with until it's used.

Generics introduce type parameters, which act like placeholders for the actual data types you specify later.

Generic Class

public class Box<T>
{
    private T _item;

    public void Add(T item)
    {
        _item = item;
    }

    public T Get()
    {
        return _item;
    }
}

--- Calling a generic class
Box<int> intBox = new Box<int>();
intBox.Add(42);
Console.WriteLine($"Int value: {intBox.Get()}");

Box<string> stringBox = new Box<string>();
stringBox.Add("Hello Generics!");
Console.WriteLine($"String value: {stringBox.Get()}");

Enter fullscreen mode Exit fullscreen mode

Generic Method

public static void PrintValues<T>(T a, T b)
{
    Console.WriteLine($"Value 1: {a}, Value 2: {b}");
}

// Usage
PrintValues(10, 20);  // Output: Value 1: 10, Value 2: 20

Enter fullscreen mode Exit fullscreen mode

we can use reference type also with generics

public static void Swap<T>(ref T a, ref T b)
{
    T temp = a;
    a = b;
    b = temp;
}

// Usage
int x = 10, y = 20;
Swap(ref x, ref y);  // Now x = 20, y = 10

Enter fullscreen mode Exit fullscreen mode

Generic Constraints

A generic constraint in C# is a way to specify the requirements that a type parameter (T) must meet for it to be used in a generic class, method, or delegate. By default, type parameters in generics can represent any type. Constraints allow you to narrow this down, ensuring the type parameter meets specific criteria.

Syntax

public class MyClass<T> where T : constraint
{
    // Class implementation
}

Enter fullscreen mode Exit fullscreen mode

Example


where T : struct (Value Type Constraint)
Restricts T to value types like int, float, bool, etc.
We cannot directly assign the dateType in the contraint.(for eg . where T:int)

public class ValueContainer<T> where T : struct
{
    public T Value { get; set; }
}

// Usage
ValueContainer<int> intContainer = new ValueContainer<int>();
// ValueContainer<string> stringContainer; // Compilation error

Enter fullscreen mode Exit fullscreen mode

where T : class (Reference Type Constraint)
Restricts T to reference types like string, classes, or interfaces.

public class ReferenceContainer<T> where T : class
{
    public T Value { get; set; }
}

// Usage
ReferenceContainer<string> stringContainer = new ReferenceContainer<string>();
// ReferenceContainer<int> intContainer; // Compilation error


Enter fullscreen mode Exit fullscreen mode
You can combine multiple constraints using a comma-separated list.

public class MultiConstraint<T> where T : class, new()
{
    public T CreateInstance()
    {
        return new T();
    }
}


Enter fullscreen mode Exit fullscreen mode

Top comments (0)