Comparisons with boxed value types

suggest change

If value types are assigned to variables of type object they are boxed - the value is stored in an instance of a System.Object. This can lead to unintended consequences when comparing values with ==, e.g.:

object left = (int)1;  // int in an object box
object right = (int)1; // int in an object box

var comparison1 = left == right;      // false

This can be avoided by using the overloaded Equals method, which will give the expected result.

var comparison2 = left.Equals(right); // true

Alternatively, the same could be done by unboxing the left and right variables so that the int values are compared:

var comparison3 = (int)left == (int)right; // true

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents