Click to See Complete Forum and Search --> : Compare 2 generic types?


Talikag
August 28th, 2008, 12:44 PM
Say I have a generic class with a generic type T, and in some point (which occurs after the instance of the class was created, i.e. the T type is now concrete) I want to compare 2 T's, like the following:

public bool Remove(T info)
{
if (this.Count == 0)
return false;
if (head.Info == info)
{
head = head.Next;
this.Count--;
return true;
}
//etc...
}

I get a precompiled error:

Error 1 Operator '==' cannot be applied to operands of type 'T' and 'T' C:\Documents and Settings\Gerbi\Local Settings\Application Data\Temporary Projects\List\List.cs 33 17 MyList

(I want to compare the address of the two T's in the memory and not their content)
Is it possible to make such comparison? If so, what should I replace the following line to?

if (head.Info == info)

hspc
August 28th, 2008, 03:24 PM
You can use:
if(head.Info.Equals(info))

Talikag
August 29th, 2008, 01:19 AM
Well, I thought about it, but what if the concrete type doesn't have the Equals method overrided?
Plus, I don't acually want to compare the content of the 2 objects. All I want to know is if the 2 objects refer to the same object in memory.

boudino
August 29th, 2008, 01:33 AM
I think it is because == operator can be overriden.

To compare references use Object.ReferenceEquals(). Using this method, you could be sure that no override method is used and the parameters are really compared by references.

JonnyPoet
August 29th, 2008, 02:00 PM
I think it is because == operator can be overriden.

To compare references use Object.ReferenceEquals(). Using this method, you could be sure that no override method is used and the
parameters are really compared by references.

As Generic Types can be everything you cannot simple compare them using '==' What should be compared that way ? adress, type, properties of a class, or is it simple a valueType and you only want to compare the value itself.

So if you want to compare in a generic method you need to restrict T and implement an interface like IEquatable<T>public class combi<T,U> where T: IEquatable<U>{
public bool test(T valT, U valU) {
return valT.Equals(valU);
}
}
This is the standard way to create generics. anyone who uses this generic needs to implement ICompareable to whatever his T is and then it will work.

Comparing adresses, just as boudino told you you can do
public bool ItemTest(U val, T val1 ) {
return object.ReferenceEqualsval, val1);
}I have tested this in an example, it compiles and it works independent if you compare value or reference types

Talikag
August 30th, 2008, 01:26 PM
Thank you guys a lot. Works great!