Does the list have <>. Is IndexOf compared by reference or value?

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 is compared by value, it should return true; if by reference, it will return false.
If it is compared by reference, and I make tinyClass a structure - will it matter?

+5
source share
5 answers

From MSDN:

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

Default , T System.IEquatable <T> , , EqualityComparer <T> . EqualityComparer <T> Object.Equals Object.GetHashCode, T.

, Equals, IEquatable <T> .

+16

Equals - .

tinyStruct, .

+2

.Equals(..). . , , true, , IEquatable.

+1
source

Be sure to implement .Equals (..) for your structure, since the default implementation can use reflection to compare each field, which is very expensive.

More details: http://blogs.microsoft.co.il/blogs/sasha/archive/2007/08.aspx

0
source

it may also be related to which instance of the class or Struct is stored in the list, due to the uniform implementation of Structs based on equality values

0
source

All Articles