tags:

views:

215

answers:

3

I need to make sure that a datatype implements the IComparable interface, and I was wondering if there was anyway to make that a requirement when you create the object?

+4  A: 

You can perhaps use generic to do this, for example:

public static T Create<T>() where T : IComparable<T>, new() {
    return new T();
}

Or if you mean "when you create the type" (in code), then no; you'd just have to remember, perhaps using unit-tests to verify that you've done it.

I recommend using the typed IComparable<T> over IComparable - it makes life a lot easier (and avoids some boxing, but that is less of an issue). Finally, remember that you can use Comparer<T>.Default and Comparer.Default in code if you want to duck-type the comparable bit (like how List<T>.Sort() works).

Marc Gravell
+1  A: 

For a generic class you can do:

public class MyType<T>
   where T:IComparable<T>
Timothy Carter
A: 

You also might want to look into Comparer<T>.Default. From what I understand it gets the IComparable<T> first, if it can't find that then it gets the IComparable version, otherwise it throws an exception.

double s = 5;
double t = 10;
int result = Comparer<double>.Default.Compare(s, t);
bendewey
I believe it will eventually throw if it can't find a suitable IComparable
JaredPar
Well, `IComparable<T>`, then `IComparable`, then throw (not `IComparer<T>` etc)
Marc Gravell
Updated to reflect, thanks.
bendewey