Enum and generic IComparable interface


S

Stefan L

Hi everybody,

when migrating to the .NET 2.0 framework we decided to encourage the use
of generic functions because they ought to run faster than their
equivalent object-implemantations.

Now I have the following problem:
I adapted my common functions to use the generic implementations of the
..NET-classes and interfaces. Now I got problems when calling my
functions with enum-types:

enum TypeOfAction {
Delete = 1,
Copy = 2,
Move = 3,
Cut = 4
}

// Find all entries with specified key and return corresponding values
public static V[] ExtractArrayEntries <T, V>
(T[] keys, V[] values, T key)
{
// next line throws with "Unable to cast ... 'TypeOfAction'
// to 'IComparable<TypeOfAction>'
IComparable<T> comparableValue = (IComparable<T>) key;
[...]
if (comparableValue.CompareTo(keys) == 0) retArray[j] = values;
[...]
}

When I use normal int's, it works fine. The old version with the
object-typed version of IComparable also worked fine with Enums.

Is there I special reason I don't see why MS didn't fit the Enum-class
with the IComparable<T>-interface?
Is there a workaround to solve this problem?

TIA,
Stefan
 
Ad

Advertisements

?

=?ISO-8859-15?Q?Lasse_V=E5gs=E6ther_Karlsen?=

Stefan said:
Hi everybody,

when migrating to the .NET 2.0 framework we decided to encourage the use
of generic functions because they ought to run faster than their
equivalent object-implemantations.

Try using IEquatable<T> instead of IComparable<T> in this case.
 
Ad

Advertisements

S

Stefan L

Wasn't appropriate in my case because I was performing a binary search
on a sorted array, so I had to perform a real comparison rather than a
check for equality.
I might have oversimplified the scenario in my example, sorry for that.

I now worked around this issue by using Comparer<T>.Default.Compare(),
which automatically switches to use the non-generic
IComparable-interface. No perfomance gain here I guess...

Thanx,
Stefan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top