From the course: C# Essential Training 2: Generics, Collections, and LINQ

Unlock the full course today

Join today to access over 24,700 courses taught by industry experts.

Generic constraints

Generic constraints

- [Instructor] I want to look at another concept around generics, which is the notion of constraints. So I'll right click over here, and we'll add a class. I'm going to call this Sorter.cs. So the idea is that I want to create a class that's going to allow me to sort something. Maybe I'll do a sorter of T, and I want to be able to then sort a set of items that are of type T. So I create a method, say public void sort. We've already got the type up there in the class definition, so now I can just say it's an array of T called items, and now I can start implementing my sort. The problem is, I don't really know what T is, and I don't know if I can compare them. For example, I could look at it and say, if I would say items, we'll assume that there's more than one for now, bad practice in our index. And we'll say, well, if that's greater than the other... But the problem is since we don't know what T stands for at this…

Contents