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

Generic constraints (where clause) in C Sharp (C#)

Choose your learning style9 modes available
Introduction
Generic constraints help you tell the computer what kind of data a generic type can work with. This keeps your code safe and clear.
When you want a method to work only with certain types of data, like numbers or objects that can be compared.
When you want to make sure a type has a specific feature, like being able to create a new instance.
When you want to reuse code but limit it to types that follow certain rules.
When you want to avoid errors by restricting types to those that implement a specific interface.
When you want to write flexible but safe code that works with many types.
Syntax
C Sharp (C#)
class ClassName<T> where T : constraint1, constraint2
{
    // class body
}

// Example constraints: struct, class, new(), base class, interface
The where clause sets rules for the generic type T.
You can use multiple constraints separated by commas.
Examples
This means T can only be a class or other reference type.
C Sharp (C#)
class DataStore<T> where T : class
{
    // T must be a reference type
}
This limits T to value types such as numbers or structs.
C Sharp (C#)
class NumberHolder<T> where T : struct
{
    // T must be a value type like int or double
}
This requires T to have a parameterless constructor so we can create new instances.
C Sharp (C#)
class Factory<T> where T : new()
{
    public T Create() => new T();
}
This ensures T can be compared, useful for sorting.
C Sharp (C#)
class ComparableList<T> where T : IComparable<T>
{
    // T must implement IComparable<T>
}
Sample Program
This program uses a generic class Factory that can create new objects of type T. The constraint where T : new() means T must have a parameterless constructor. We create a Product object and print its Name.
C Sharp (C#)
using System;

class Factory<T> where T : new()
{
    public T Create() => new T();
}

class Product
{
    public string Name = "Sample Product";
}

class Program
{
    static void Main()
    {
        var factory = new Factory<Product>();
        Product p = factory.Create();
        Console.WriteLine(p.Name);
    }
}
OutputSuccess
Important Notes
You cannot use where constraints to restrict to specific values, only types or features.
The new() constraint must come last if combined with others.
Constraints help catch errors early, before running the program.
Summary
Generic constraints limit what types can be used with generics.
Use where clause to set these rules clearly.
Constraints make your code safer and easier to understand.