← Back to C# Course | Chapter 11: Generics | Lesson 3 of 6

Generic Constraints

Generic constraints are rules about what types are allowed in a generic, like a club that only accepts people who can swim. They let the code safely use certain features of the type.

In this page:

  1. Generic Constraints
Syntax
csharp
static T MethodName<T>(T a, T b) where T : IComparable<T>
{
    // body
}

class ClassName<T> where T : class, new() { }

Generic Constraints

Constraints restrict what types can be used as a generic's type argument, using where T : ....

Common constraints require a class, a struct, a parameterless constructor (new()), or implementation of a specific interface. Constraints let generic code safely call members that aren't available on every possible type.

Note: Use where T : IComparable<T> when your generic method needs to compare two values of type T.

Example: Generic Constraints

markup
using System;

class Program
{
    static T Max<T>(T a, T b) where T : IComparable<T>
    {
        return a.CompareTo(b) > 0 ? a : b;
    }

    static void Main(string[] args)
    {
        Console.WriteLine(Max(3, 7));
        Console.WriteLine(Max("apple", "banana"));
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Forgetting where T : new() and then calling new T(), which is a compile error.
  2. Putting the constraints in the wrong order, such as new() before a class constraint.
  3. Passing a type that does not satisfy the constraint, which is a compile error.
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.