Exercises in this lecture   Go to the notes, in which this exercise belongs -- Keyboard shortcut: 'u'   Alphabetic index   Course home   

Exercise solution:
Equality of value types and reference types

We study the following program:

using System;

class WorderingAboutEquality{

  public static void Main(){
    int i = 5,
        j = 5;

    object m = 5,
           n = 5;  

    Console.WriteLine(i == j);
    Console.WriteLine(m == n);


i == j is value comparison, and as such the value of i == j is true.

First notice that object is an alias for System.Object.

The expression m == n compares references because the two 5-values are boxed when assigned to values of a reference type, see the section about boxing and unboxing. The == operator in m == n is determined by the static type of m and n, namely object. For m and n of type object, == will lead to comparison of references. m and n reference two different objects (which hold the same value). Therefore the value of the boolean expression m == n is false.