Another bug

time to read 1 min | 168 words

Apperantely I've discovered a bug in .NET where two identical strings are compared through object reference.

Consider the following code:

using

System;

using

System.Collections;

using

System.Collections.Specialized;

using

System.Reflection;

namespace

test2

{

class Class1

{

[STAThread]

static void Main(string[] args)

{

ReallyStrangeBug();

}

public static void ReallyStrangeBug()

{

HybridDictionary dic = new HybridDictionary();

foreach(MemberInfo member in typeof(object).GetMembers(BindingFlags.Public | BindingFlags.Instance))

dic.Add(member.Name,member);

Console.WriteLine("Using Objects comparision:");

Console.WriteLine(objectExistIn("ToString",dic.Keys));

Console.WriteLine("Using strings comparision:");

Console.WriteLine(stringExistIn("ToString",dic.Keys));

Console.WriteLine(dic.Contains("ToString"));

}

private static bool objectExistIn(object o, IEnumerable enumerable)

{

foreach(object current in enumerable)

{

Console.WriteLine("'{0}' == '{1}': {2}",o,current,o==current);

if(o==current)

return true;

}

return false;

}

private static bool stringExistIn(string o, IEnumerable enumerable)

{

foreach(string current in enumerable)

{

Console.WriteLine("'{0}' == '{1}': {2}",o,current,o==current);

if(o==current)

return true;

}

return false;

}

}

}

 

This produce the following output:

Using Objects comparision:
'ToString' == 'GetHashCode': False
'ToString' == 'Equals': False
'ToString' == 'ToString': False
'ToString' == 'GetType': False
'ToString' == '.ctor': False
False
Using strings comparision:
'ToString' == 'GetHashCode': False
'ToString' == 'Equals': False
'ToString' == 'ToString': True
True
True
Press any key to continue

 

Reason unknown