Generic Constraints
In this page:
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
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"));
}
}
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: