dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
19.02k stars 4.03k forks source link

C# 9 Records not providing an override of == when running on .Net Core 3 #53990

Closed epNickColeman closed 3 years ago

epNickColeman commented 3 years ago

Version Used: .Net 3.1.403 C# 9.0

Steps to Reproduce:

  1. Create two equivalent records
  2. Compare with .equals, observe true
  3. Compare with ==, observe false
        [Test]
        public void RecordsAreEqualByValue()
        {
            var zaphod1 = new Person(firstName: "Zaphod", lastName: "Beeblebrox");
            var zaphod2 = new Person(firstName: "Zaphod", lastName: "Beeblebrox");

            zaphod1.Should().Be(zaphod2); // Passes
            (zaphod1 == zaphod2).Should().BeTrue(); // Fails in .net core 3, passes in .net 5
        }

Expected Behavior: I expect == to be overridden regardless of framework version Actual Behavior: == is not overridden in .net core3

Youssef1313 commented 3 years ago

The following prints true for me in .NET Core 3.

using System;

namespace System.Runtime.CompilerServices
{
    class IsExternalInit { }
}

namespace ConsoleApp3
{
    record Person(string A, string B);

    class Program
    {
        static void Main(string[] args)
        {
            var a = new Person("a", "b");
            var b = new Person("a", "b");
            Console.WriteLine(a == b);
        }
    }
}

image

epNickColeman commented 3 years ago

Ah, I see it works when targeting 3.1, but using the .net 5.0.300 SDK. I had the following global.json

{
  "sdk": {
    "version": "3.1.300",
    "rollForward": "latestFeature"
  }
}

which means it was built with 3.1.403 version of the compiler - so I guess this is we can use the 5.0 SDK to target 3.1 while still necessary, so this can probably be closed. Thanks for taking the time to look at this.

huoyaoyuan commented 3 years ago

C# 9 was shipped with .NET 5. Are you sure you can compile C# 9 with 3.1 SDK?