By BanksySan


2018-05-16 15:08:57 8 Comments

I understand interning strings and not value/reference types are compared but this behavior is confusing me.

using System;

internal static class StringEqualities
{
    private static void Main()
    {
        const string s1 = "Hello World";
        var helloWorldCharArray = s1.ToCharArray();
        var s2 = new string(helloWorldCharArray);
        var o1 = (object) s1;
        Console.WriteLine();
        Console.WriteLine("s1 = '{0}'.", s1);
        Console.WriteLine("s2 = '{0}'.", s2);
        Console.WriteLine("o2 = '{0}'.", o1);
        Console.WriteLine();
        Console.WriteLine("s1 == s2 ? {0}", s1 == s2);  // True
        Console.WriteLine("o1 == s1 ? {0}", o1 == s1);  // True
        Console.WriteLine("o1 == s2 ? {0}", o1 == s2);  // False
        Console.WriteLine("s2 == o1 ? {0}", s2 == o1);  // False
        Console.WriteLine();
        Console.WriteLine("o1.Equals(s2) ? {0}", o1.Equals(s2));  // True
        Console.WriteLine("s2.Equals(o1) ? {0}", s2.Equals(o1));  // True
    }
}

The last two comparisons (using Equals) return true. I'd expected them to return false, the same as == did.

I've got a working example here https://repl.it/@BanksySan/String-Equality.

Why does Equals have a different behavior to ==?

NB The suggested answer here: https://stackoverflow.com/a/814880/442351 does explain that == is a reference equality whereas Equals is the overridden method. This doesn't explain the behavior 100% though.

The crux of the behavior is that the Equals method is overridden and so the string implementation is invoked in both cases. The operator implementation == is not. The implementation of the type it is cast to is implemented regardless of whether there is another implementation in the child type (i.e. object's == is invoked but string's Equals is invoked).

0 comments

Related Questions

Sponsored Content

59 Answered Questions

[SOLVED] What is the difference between String and string in C#?

  • 2008-08-10 07:18:02
  • Lance Fisher
  • 847131 View
  • 5207 Score
  • 59 Answer
  • Tags:   c# .net string types

22 Answered Questions

[SOLVED] Case insensitive 'Contains(string)'

12 Answered Questions

[SOLVED] How to convert UTF-8 byte[] to string?

9 Answered Questions

[SOLVED] How to escape braces (curly brackets) in a format string in .NET

37 Answered Questions

11 Answered Questions

[SOLVED] C# Interfaces. Implicit implementation versus Explicit implementation

  • 2008-09-27 10:56:16
  • Seb Nilsson
  • 130882 View
  • 551 Score
  • 11 Answer
  • Tags:   c# .net interface

11 Answered Questions

[SOLVED] Can't operator == be applied to generic types in C#?

4 Answered Questions

[SOLVED] Casting Deriving Class as Base Class

1 Answered Questions

3 Answered Questions

[SOLVED] Object.Equals clarification in C#?

  • 2013-02-16 21:33:27
  • Royi Namir
  • 127 View
  • 1 Score
  • 3 Answer
  • Tags:   c# .net equals

Sponsored Content