0
0
CsharpConceptBeginner · 3 min read

What is where keyword in generics C# and How to Use It

The where keyword in C# generics is used to set restrictions on the types that can be used as arguments for a generic type or method. It ensures that the type parameter meets certain requirements like implementing an interface, inheriting a class, or having a parameterless constructor.
⚙️

How It Works

Imagine you have a toolbox, but you want to make sure only certain tools fit inside it. The where keyword acts like a rule that says, "Only tools of a certain kind can go in this box." In programming, this means you can tell your generic code to only accept types that follow specific rules.

For example, you might want a generic method to only accept types that can be compared or types that have a default way to create an instance. The where keyword lets you specify these rules clearly, so the compiler helps you catch mistakes early.

This makes your code safer and easier to understand because you know exactly what kind of types your generic code expects.

💻

Example

This example shows a generic class that only accepts types that implement the IComparable interface, so it can compare two values safely.

csharp
using System;

class ComparableBox<T> where T : IComparable<T>
{
    private T value;

    public ComparableBox(T value)
    {
        this.value = value;
    }

    public bool IsGreaterThan(T other)
    {
        return value.CompareTo(other) > 0;
    }
}

class Program
{
    static void Main()
    {
        var box = new ComparableBox<int>(10);
        Console.WriteLine(box.IsGreaterThan(5));
        Console.WriteLine(box.IsGreaterThan(15));
    }
}
Output
True False
🎯

When to Use

Use the where keyword when you want to make sure your generic code only works with types that have certain features. For example:

  • If your method needs to compare items, require IComparable.
  • If you want to create new instances inside your generic class, require a parameterless constructor with new().
  • If your code needs to work only with classes or structs, you can restrict types to class or struct.

This helps prevent errors and makes your code easier to maintain because the rules are clear.

Key Points

  • The where keyword sets rules for generic type parameters.
  • It can require a type to be a class, struct, have a constructor, or implement interfaces.
  • Helps catch errors at compile time by restricting allowed types.
  • Makes generic code safer and clearer.

Key Takeaways

The where keyword restricts generic types to meet specific requirements.
It ensures safer and clearer generic code by enforcing type rules.
Common constraints include interfaces, base classes, constructors, and value/reference types.
Use where to prevent invalid types and catch errors early during compilation.