471,317 Members | 1,519 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,317 software developers and data experts.

Enum and generic IComparable interface

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
2 5858
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
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.

Similar topics

1 post views Thread by Ning Hu | last post: by
3 posts views Thread by =?Utf-8?B?R0I=?= | last post: by
6 posts views Thread by Jon | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.