Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to force my container class to only accept objects that implement IComparable?

Tags:

c#

I am learning C#. Doing the below exercises to make use of features.

I have this class acting as my container:

class myContainer<T> : List<T>

When I add this struct to the container it works fine because it has an implementation of IComparable

interface bla<T> : IComparable<T> {}
struct IString : bla<IString>

When I add a class that has not implemented IComparable through an interface or directly, I get an error at runtime if I do something like Sort()

What's the best way to force my container class to only accept objects that implement IComparable ?

thanks

like image 830
Jason Levens Avatar asked Nov 30 '22 18:11

Jason Levens


1 Answers

class myContainer<T> : List<T>
    where T : IComparable<T>
{
    ...
}

If possible, you might want to also consider supporting IComparable (the non-generic version) for your class.

This MSDN article on generic constraints has more information on the where expression.

like image 120
David Pfeffer Avatar answered Mar 30 '23 00:03

David Pfeffer