Skip to content
Justice Tech School

Generics

Generic classes and methods work with any type, with constraints.

Example
static T Max<T>(T a, T b) where T : IComparable<T> => a.CompareTo(b) > 0 ? a : b;
Console.WriteLine(new Box<int>(5).Value);
Console.WriteLine(Max("a", "b"));

class Box<T> { public T Value { get; } public Box(T v) => Value = v; }

Exercise

Constraint keyword.

 T : IComparable<T>

Quiz Test

What does where T : class do?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.