Testing for implementation if IComparable<T> regarless of <T>

  • Thread starter Thread starter Samuel R. Neff
  • Start date Start date
S

Samuel R. Neff

You can you program against generic interfaces generically?

For example, how can I make the following code which works for the
non-generic interface also work for the generic counterparts?

public bool Equivalent(ArrayList x, ArrayList y) {
if (x[0] is IComparable) {
x.Sort();
x.Sort();
}
...
}

The above does not work with generic counterparts because
IComparable<T> does not extend IComparable (similarly IList<> does not
extend IList even though List<> implements both, ditto for
IDictionary<> vs IDictionary).

As a workaround I know I can always call Sort() and catch the error
that's thrown when the contained items are not IComparable, but this
issue of dealing with generics when the parameterized type is not
known has come up before.

Thanks,

Sam
 
Hi,

I do not understand your question completely, so I will make a guess.

First you call Sort twice in X (may be a typo).
Also what is the point in seeing if x[0] is comparable? ArrayList can
contain several types and x[1] could not implement IComparable.
The same occur with y.
 
Yes, it's possible that the ArrayList will have different object
types. I happen to know it will never happen in my app, and even
better with generics we can guarantee it won't happen.

Yes the double x.Sort() call was a typo--intended to be x.Sort() and
y.Sort().

Sam



Hi,

I do not understand your question completely, so I will make a guess.

First you call Sort twice in X (may be a typo).
Also what is the point in seeing if x[0] is comparable? ArrayList can
contain several types and x[1] could not implement IComparable.
The same occur with y.

Samuel R. Neff said:
You can you program against generic interfaces generically?

For example, how can I make the following code which works for the
non-generic interface also work for the generic counterparts?

public bool Equivalent(ArrayList x, ArrayList y) {
if (x[0] is IComparable) {
x.Sort();
x.Sort();
}
...
}
 
I wouldn't personally get much into the realms of mising generic and
non-generic like this, but in the generic (i.e.
System.Collections.Generic) sense, Comparer<T>.Default will check for
a range of ways for comparing T, returning an IComparer<T>:
* checks for IComparable<T>
* same, using Nullable<T>
* then switches to Comparer.Default:
* checks for equality / nulls
* special case for strings
* checks for IComparable
* throws

So using Comparar<T>.Default is a good choice if you don't know T in
advance. Not sure how much of that is documented and guaranteed, but
that's what it does in 2.0 ;-p

Marc
 
Back
Top