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?
To get the index of an item in a single line, use the FindIndex() and Contains() method. int index = myList. FindIndex(a => a.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With