C# Language Built-in Types Comparisons with boxed value types

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

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


Got any C# Language Question?