tags:

views:

137

answers:

5

What's the syntax to require T also be IComparable in this class definition?

public class EditItems<T> : Form
+7  A: 
public class EditItems<T> : Form where T : IComparable
Dario
+3  A: 

Use a type constraint (see MSDN):

public class EditItems<T> : Form where T : IComparable
Lucas Jones
+3  A: 
public class EditItems<T> : Form where T : IComparable
bruno conde
+3  A: 
public class EditItems<T> : Form where T : IComparable
{...}
Bryan Hunter
+11  A: 

You can use just where T : IComparable as shown by other answers. I find it's typically more helpful to constrain it with:

public class EditItems<T> : Form where T : IComparable<T>

That says it has to be a type which is comparable with itself.

For one thing, for value types this avoids boxing. For another, it means you're less likely to try to compare two values which aren't really comparable.

Jon Skeet
Not asked for but still true ;-)
Dario
The generic version is more type-safe, but if you want something akin to contravariance in the IComparable implementation you can only use the non-generic version, until C#4 comes out
thecoop
I wondered if anyone would catch the IComparable<T>... I actually picked it because it would be an interface everyone would know so I could focus the question on the syntax (I'm not *really* using IComparable). Thanks for the thorough response though!
Austin Salonen