Re: Compare 2 generic types?
You can use:
Code:
if(head.Info.Equals(info))
Re: Compare 2 generic types?
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.
Re: Compare 2 generic types?
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.
Re: Compare 2 generic types?
Quote:
Originally Posted by boudino
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>
Code:
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
Code:
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
Re: Compare 2 generic types?
Thank you guys a lot. Works great!