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

Generic Constraints

In this page:

  1. Generic Constraints

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"));
    }
}
🔒

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.