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.04k stars 4.03k forks source link

Unexpected coalesce operation is applied to `char.ToString()` involved into concatenation with a null or empty constant string #72232

Open AlekseyTs opened 8 months ago

AlekseyTs commented 8 months ago
        [Fact]
        public void Concat()
        {
            var source = """
            using System;

            public class Test
            {
                static void Main()
                {
                    var c = 'c';
                    Console.Write(M2(c));
                }

                static string M2(char c) => c + (string)null;
            }
            """;

            var comp = CreateCompilation(source, options: TestOptions.ReleaseExe, targetFramework: TargetFramework.Net80);

            var verifier = CompileAndVerify(compilation: comp, expectedOutput: RuntimeUtilities.IsCoreClr8OrHigherRuntime ? "c" : null, verify: RuntimeUtilities.IsCoreClr8OrHigherRuntime ? default : Verification.Skipped);

            verifier.VerifyDiagnostics();
            verifier.VerifyIL("Test.M2", """
            {
              // Code size       17 (0x11)
              .maxstack  2
              IL_0000:  ldarga.s   V_0
              IL_0002:  call       "string char.ToString()"
              IL_0007:  dup
              IL_0008:  brtrue.s   IL_0010
              IL_000a:  pop
              IL_000b:  ldstr      ""
              IL_0010:  ret
            }
            """);
        }

Expected: The M2 body should be just the char.ToString() call without any additional conditional logic.

AlekseyTs commented 8 months ago

The same issue probably exists with other primitive struct types.