473,387 Members | 1,532 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

Equality and generics

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[i]==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[i].Equals(item), of course...
Jun 29 '06 #1
7 1803
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?
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Giulio Petrucci" <gi*************@SUPERCALIFRAGILISTICHESPIRALIDOSO .com>
wrote in message news:OP**************@TK2MSFTNGP04.phx.gbl...
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[i]==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[i].Equals(item), of course...

Jun 29 '06 #2
hi giulio,

you should also overload == operator for your class...you can find very
useful sample at the following article:

http://www.samspublishing.com/articl...seqNum=15&rl=1
http://www.csharpfriends.com/Article...x?articleID=88
http://msdn.microsoft.com/library/de...ngTutorial.asp

hope that helps,
AMB

"Giulio Petrucci" wrote:
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[i]==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[i].Equals(item), of course...

Jun 29 '06 #3
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

Jun 29 '06 #4
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
Jun 29 '06 #5
hi,

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

thanks,
AMB

"Giulio Petrucci" wrote:
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

Jun 29 '06 #6
AMB,

This is not correct. You can overload == on your generic class, but not
for the type argument T.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"ahmet mithat bostanci" <ah*****************@discussions.microsoft.com>
wrote in message news:38**********************************@microsof t.com...
hi,

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

thanks,
AMB

"Giulio Petrucci" wrote:
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

Jun 29 '06 #7
Try this:

int GetIndex(T item) {
IEqualityComparer<T> comparer = EqualityComparer<T>.Default;
for (int i = 0; i < array.Length; i++) {
if (comparer.Equals(array[i],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
Jun 30 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

40
by: Ike Naar | last post by:
In K&R "The C++ programming language (2nd ANSI C edition), the reference manual states (paragraphs 7.9 and 7.10) that pointer comparison is undefined for pointers that do not point to the same...
4
by: Matt Burland | last post by:
I'm a little confused about the way the default equality operator works with classes. Here's the situation, I have two comboboxes that are each filled with different object (i.e. ComboBox1 contains...
27
by: Bernardo Heynemann | last post by:
How can I use Generics? How can I use C# 2.0? I already have VS.NET 2003 Enterprise Edition and still can´t use generics... I´m trying to make a generic collection myCollection<vartype> and...
23
by: Luc Vaillant | last post by:
I need to initialise a typed parameter depending of its type in a generic class. I have tried to use the C++ template form as follow, but it doesn't work. It seems to be a limitation of generics...
12
by: Michael S | last post by:
Why do people spend so much time writing complex generic types? for fun? to learn? for use? I think of generics like I do about operator overloading. Great to have as a language-feature, as...
37
by: spam.noam | last post by:
Hello, Guido has decided, in python-dev, that in Py3K the id-based order comparisons will be dropped. This means that, for example, "{} < " will raise a TypeError instead of the current...
9
by: sloan | last post by:
I'm not the sharpest knife in the drawer, but not a dummy either. I'm looking for a good book which goes over Generics in great detail. and to have as a reference book on my shelf. Personal...
1
by: Vladimir Shiryaev | last post by:
Hello! Exception handling in generics seems to be a bit inconsistent to me. Imagine, I have "MyOwnException" class derived from "ApplicationException". I also have two classes...
7
by: SpotNet | last post by:
Hello NewsGroup, Reading up on Generics in the .NET Framework 2.0 using C# 2005 (SP1), I have a question on the application of Generics. Knowingly, Generic classes are contained in the...
13
by: rkausch | last post by:
Hello everyone, I'm writing because I'm frustrated with the implementation of C#'s generics, and need a workaround. I come from a Java background, and am currently writing a portion of an...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.