Object.Equals is virtual, but Object.operator == does not use it in C #?

I was struck by the strange "asymmetry" in C #, which I really do not understand. See the following code:

using System;
using System.Diagnostics;
namespace EqualsExperiment
{
    class Program
    {
        static void Main(string[] args)
        {
            object apple = "apple";
            object orange = string.Format("{0}{1}", "ap", "ple");
            Console.WriteLine("1");
            Debug.Assert(apple.Equals(orange));
            Console.WriteLine("2");
            Debug.Assert(apple == orange);
            Console.WriteLine("3");
        }
    }
}

This may be obvious to all of you, the .NET guru, but the 2nd statement does not work.

In Java, I found out that == is synonymous with what is called Object.ReferenceEquals. In C #, I thought Object.operator == was using Object.Equals, which is virtual, so it is overridden in the System.String class.

Can someone explain why 2nd claim to crash in C #? Which of my assumptions are bad?

+5
source share
2 answers

== , , .

== , Equals:

public static bool operator ==(string a, string b) {
  return Equals(a, b);
}

, , ==, , ReferenceEquals .

, , , , .

+7

, . , == object ( object), . string, == string , .

+6

All Articles