By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,727 Members | 1,258 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,727 IT Pros & Developers. It's quick & easy.

Enum and generic IComparable interface

P: n/a
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[i]) == 0) retArray[j] = values[i];
[...]
}

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
Nov 28 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Stefan L wrote:
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.

--
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:la***@vkarlsen.no
PGP KeyID: 0x2A42A1C2
Nov 28 '05 #2

P: n/a
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
Lasse Vågsæther Karlsen schrieb:
Stefan L wrote:
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.

Nov 28 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.