Equality and generics

G

Giulio Petrucci

Hi everybody,

I'm implementing a sort of my own generic collection.
It has a method that returns an int representing the index for a particular
index. If I try to compile the code below:

class MyCollection<T> : ICollection<T> {

T[] array;
MyCollection() {
array = new T[];
}

int GetIndex(T item) {

for (int i=0; i<array.Length; i++) {
if (array==item)
return i;
}
return -1;
}

}

I get this compiler error:

Operator '==' cannot be applied to operands of type 'T' and 'T'

That's because there's no definition for == in T (that's actually a generic
type)?

Thanks,
Giulio

p.s. I solved using array.Equals(item), of course...
 
N

Nicholas Paldino [.NET/C# MVP]

Giulio,

Yes, this is right. The compiler doesn't know what T is going to be, so
it doesn't know how to compare them.

On a side note, why not use the List<T> class and the Find method?
 
G

Giulio Petrucci

Hi Nicholas and thank you for your reply,

Nicholas Paldino [.NET/C# MVP] ha scritto:
On a side note, why not use the List<T> class and the Find method?

Well, I'm not using a List<T>.
I'm implementing something like a Set and instead of wrapping a List<T> I
preferred write it from scratch for two reasons:
1) to improve performance (but it's not the main reason)
2) to make some _practice_, as I'm a C# newbie and I think that performe
something like this can be very useful to me.

Kind regards,
Giulio
 
G

Giulio Petrucci

ahmet mithat bostanci ha scritto:
you should also overload == operator for your class...you can find very

But can I overload an operator for a _generic_ type T?

Thanks,
Giulio
 
G

Guest

hi,

yes, you can...by the way, as far as i know, you should also overload !=
operator when you overload == operator...

thanks,
AMB
 
N

Nicholas Paldino [.NET/C# MVP]

AMB,

This is not correct. You can overload == on your generic class, but not
for the type argument T.
 
M

Marc Gravell

Try this:

int GetIndex(T item) {
IEqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < array.Length; i++) {
if (comparer.Equals(array,item))
return i;
}
return -1;
}

In a recent post I provided detailed metrics to show that
EqualityComparer<T>.Default is performant; in particular, note that this
will avoid having to box the items for valuee-types, which should make it
much quicker than flat Equals() [for value types].

Marc
 

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