tags:

views:

839

answers:

5
List<tinyClass> ids = new List<tinyClass();
ids.Add(new tinyClass(1, 2));

bool b = ids.IndexOf(new tinyClass(1, 2)) >= 0; //true or false?

If it compares by value, it should return true; if by reference, it will return false.
If it compares by reference, and I make tinyClass a struct - will that make a difference?

+12  A: 

From MSDN:

This method determines equality using the default equality comparer EqualityComparer<T>.Default for T, the type of values in the list.

The Default property checks whether type T implements the System.IEquatable<T> generic interface and if so returns an EqualityComparer<T> that uses that implementation. Otherwise it returns an EqualityComparer<T> that uses the overrides of Object.Equals and Object.GetHashCode provided by T.

Seems like it uses the Equals method, unless the stored class implements the IEquatable<T> interface.

OregonGhost
+1  A: 

It depends on the object's implementation of .Equals(..). By default for an object, the references are compared. If you did change it to a struct, then I believe it would evaluate to true based on the equality of the private members, but it would still be more programmically sound to implement IEquatable.

Timothy Carter
+1  A: 

For a class, with the default implementation of Equals - it will compare by reference.

If you change it to a tinyStruct, it will compare it by value.

Tom Ritter
A: 

Be sure to implement .Equals(..) for your struct, as the default implementation may use reflection to compare each field, which is very expensive.

Read more at: http://blogs.microsoft.co.il/blogs/sasha/archive/2007/08.aspx

John Gibb
A: 

it also, may be related to which of Class or Struct instance is kept in list, because of Structs equal implementation is based on values equality