Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does List<String>.Contains(mystring) do a reference comparison or a value comparison?

Tags:

string

c#

Does List.Contains(mystring) do a reference comparison or a value comparison? Eg I have this code:

/// <summary>
/// If the value isn't null or an empty string, 
/// and doesn't exist in the list, it adds it to the list
/// </summary>
static void AddToListIfNotEmpty(List<string> thelist, SqlString val)
{
  string value = val.ToString().Trim();
  if (!string.IsNullOrEmpty(value))
  {
    bool found = false;
    foreach (string x in thelist) if (x == value) found = true;
    if (!found) thelist.Add(value);
  }
}

Can i simplify the foreach and following line to:

if (!thelist.Contains(value)) thelist.Add(value);

Thanks

like image 721
Chris Avatar asked Dec 03 '22 07:12

Chris


2 Answers

IList<T> uses Comparator<T>.Default to do the comparisons, and in turn that compares by value for String objects.

If you wanted to, you could move your items to an IDictionary<T, bool> or something similar, where you can specify your IComparator - specifying one that checks for reference. (even though in that case, you're better off with the foreach loop)

If you can use LINQ, you could create a statement there with a reference comparison, too.

like image 74
Aviad Ben Dov Avatar answered Dec 04 '22 22:12

Aviad Ben Dov


From MSDN of List<T>.Contains

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 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.

Looking at reflector (and by the principle of least surprise), String Equality has value type semantics - so they are equal if they have the same strings. Both Equals(Object) and IEquatable.Equals(T) delegate to String::EqualsHelper

like image 30
Gishu Avatar answered Dec 04 '22 21:12

Gishu