if (<object> == )

后端 未结 3 475
故里飘歌
故里飘歌 2021-01-19 23:12

I can\'t understand, why the if statement in the picture below returns false. I hope you can explain it to me.

You can see, that the values and the typs

3条回答
  •  一整个雨季
    2021-01-19 23:40

    When you cast an int to an object, you are creating a new object. This is referred to as boxing.

    Any comparison will then be an object comparison. With objects, the == operator will check if the references are the same. It will not check if the two variable reference equivalent objects, it will check if the two variables reference one object.

    If you want to perform an int comparison, you must convert it back to an integer (unbox it).

    Alternatively, you can use Equals instead of the == operator.

    Here's a piece of code which demonstrates this:

    using System;
    
    public class Program
    {
        public static void Main()
        {
            int n = 3;
            object o1 = n;
            object o2 = n;
            Console.WriteLine("o1 == o2 is {0}", o1 == o2);
            Console.WriteLine("o1.Equals(o2) is {0}", o1.Equals(o2));
            Console.WriteLine("(int)o1 == (int)o2 is {0}", (int)o1 == (int)o2);
    
        }
    }
    

    The output:

    o1 == o2 is False

    o1.Equals(o2) is True

    (int)o1 == (int)o2 is True

提交回复
热议问题