Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does List<>.IndexOf compare by reference or value?

Tags:

c#

.net

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?

like image 268
Tom Ritter Avatar asked Oct 06 '08 20:10

Tom Ritter


People also ask

How do you get an index of an element in a list C#?

To get the index of an item in a single line, use the FindIndex() and Contains() method. int index = myList. FindIndex(a => a.

Does list have Index C#?

The IndexOf method returns the first index of an item if found in the List. C# List<T> class provides methods and properties to create a list of objects (classes). The IndexOf method returns the first index of an item if found in the List.


1 Answers

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.

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

like image 181
OregonGhost Avatar answered Oct 18 '22 20:10

OregonGhost