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
2009-03-27 13:05:07
+1
A:
For a generic class you can do:
public class MyType<T>
where T:IComparable<T>
Timothy Carter
2009-03-27 13:06:56
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
2009-03-27 13:10:08
I believe it will eventually throw if it can't find a suitable IComparable
JaredPar
2009-03-27 13:17:34
Well, `IComparable<T>`, then `IComparable`, then throw (not `IComparer<T>` etc)
Marc Gravell
2009-03-27 13:26:31
Updated to reflect, thanks.
bendewey
2009-03-27 13:53:53