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:
Syntax
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
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
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
- Forgetting
where T : new()and then callingnew T(), which is a compile error. - Putting the constraints in the wrong order, such as
new()before a class constraint. - 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: