1

I recently started coding in C# and writing ASP.NET MVC apps. I was doing something similar to this:

var hashtable =  new Hashtable();
hashtable.Add("First", 12);
hashtable.Add("Second", 12);

if(hashtable["First"] == hashtable["Second"])
{
    Console.WriteLine("Equal");
}
else{
    Console.WriteLine("Not Equal");
}

It always outputs Not Equal. A while later I realized it was the effect of boxing. However, if I write the following:

var hashtable =  new Hashtable();
hashtable.Add("First", 12);
hashtable.Add("Second", 12);

dynamic ViewBag = new System.Dynamic.ExpandoObject();
ViewBag.hashtable = hashtable;

if(ViewBag.hashtable["First"] == ViewBag.hashtable["Second"])
{
    Console.WriteLine("Equal");
}
else
{
    Console.WriteLine("Not Equal");
}

It always outputs Equal.

What is the underlying mechanism that is causing this difference?

foresightyj
  • 1,836
  • 2
  • 21
  • 40
  • "Equality is complicated.". This might help you. http://stackoverflow.com/questions/21273890/what-is-the-difference-between-and-equals-for-primitives-in-c – Adrian Nasui Dec 11 '14 at 09:42
  • @AdrianNasui Thanks but I think the link you referenced is a different kind of problem. My confusion is not about reference equality vs value equality or implicity casting of short to int but what is causing `ViewBag.hashtable["First"]` to be automatically unboxed while `hashtable["First"]` is still boxed. – foresightyj Dec 11 '14 at 09:50
  • 1
    Sorry, gave it a bit more thought and I understood that your question is not about ref equality. Good question I am waiting for the answer. – Adrian Nasui Dec 11 '14 at 09:51

0 Answers0