The following code fails. Why?

int a = 5;
int b = 5;

object oa = a;
object ob = b;

Debug.Assert(oa == ob, "oa is not equal ob");

Showing Answers 1 - 5 of 5 Answers

the main reason behind the code failure is using == operartor instead of Equal.
when we are using == than the refrence object should be same.
means
we are comapring refrence of a and b but instead if we use this code than == return true

int a=5;
int b=5;

object o1=a;
object o2=a;

debug.assert(o1==o2,"") 

other way----------------

int a=5;
int b=5;

object o1=a;
object o2=b;

debug.assert(o1.Equal(o2))

  Was this answer useful?  Yes

PeterVH

  • Aug 19th, 2011
 

The "==" operand on the 2 int's is comparing value types. Here the content is compared.

After boxing the value types into objects, i.e. reference types, the "==" operand compares the references (memory adresses) of both objects. And even though they both point to a value of 5 somewhere in memory, they each point to their own "stored number 5 in memory).

As other stated, you have to use Equals to copare their content.

(Would be fun to modify the question to use an ArrayList (boxed values) and ask if it would make a difference if we used the Generic list List)

Code
  1.         private void button1_Click(object sender, EventArgs e)

  2.         {

  3.             const int valueTypeA = 5;

  4.             const int valueTypeB = 5;

  5.  

  6.             Debug.WriteLine(valueTypeA == valueTypeB); // true

  7.             Debug.WriteLine(valueTypeA.Equals(valueTypeB)); // true

  8.             Debug.WriteLine(valueTypeB.Equals(valueTypeA)); // true

  9.  

  10.             object boxedA = valueTypeA;

  11.             object boxedB = valueTypeB;

  12.  

  13.             Debug.WriteLine(boxedA.Equals(boxedB)); // true

  14.             Debug.WriteLine(boxedB.Equals(boxedA)); // true

  15.  

  16.             Debug.WriteLine(boxedA == boxedB); // false

  17.  

  18.             // Addendum to the question to show the difference between the old arraylist and the

  19.             // generic list (which doesn't box if it is a value type)

  20.             var arrayList = new ArrayList { valueTypeA, valueTypeB };

  21.             Debug.WriteLine(arrayList[0] == arrayList[1]); // false as they are boxed

  22.  

  23.             var listOfInts = new List<int> { valueTypeA, valueTypeB };

  24.             Debug.WriteLine(listOfInts[0] == listOfInts[1]); // true because generics keep the value type

  25.         }

chidski

  • Oct 17th, 2013
 

Given code fails bcoz. debug result is wrong.. Please see below

int a = 5;
int b = 5;

object oa = a;
object ob = b;

Debug.Assert(oa != ob, "oa is not equal ob"); --- gets skipped

Debug.Assert(oa == ob, "oa is equal ob"); --- gets executed

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions