== vs. Object.Equals(object) in .NET

前端 未结 9 2258
无人及你
无人及你 2020-11-28 22:33

So, when I was a comparative novice to the novice I am right now, I used to think that these two things were syntactic sugar for each other, i.e. that using one over the oth

9条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 23:23

    Operator == and Equals() both are same while we are comparing values instead of references. Output of both are same see below example.

    Example

        static void Main()
        {
            string x = " hello";
            string y = " hello";
            string z = string.Copy(x);
            if (x == y)
            {
                Console.WriteLine("== Operator");
            }
            if(x.Equals(y))
            {
                Console.WriteLine("Equals() Function Call");
            }
            if (x == z)
            {
                Console.WriteLine("== Operator while coping a string to another.");
            }
            if (x.Equals(y))
            {
                Console.WriteLine("Equals() Function Call while coping a string to another.");
            }
        }
    

    Output:

      == Operator
      Equals() Function Call
      == Operator while coping a string to another.
      Equals() Function Call while coping a string to another.
    

提交回复
热议问题