Skip to content

IDE0004 incorrectly reported when casting from nullable enum to nullable int; applying codefix results in non-compilable code #60292

@IanKemp

Description

@IanKemp

Version Used:

Visual Studio 2022 version 17.1.1
#error version = Compiler version: '4.1.0-5.22109.6 (0c82c41)'. Language version: 9.0.

Steps to Reproduce:

Create a new .NET 5.0 console application and overwrite the content of Program.cs with the following:

using System;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            for (var i = 0; i < 100; i++)
            {
                bool should = Should();
                Test? test = ShouldTest();
                int? testId = should ? (int?)test : null; // incorrect IDE0004

                Console.WriteLine($"should: {should}, test: {test}, testId: {testId}");
            }
        }

        private static bool Should()
        {
            return new Random().Next() % 2 == 0;
        }

        private static Test? ShouldTest()
        {
            var value = new Random().Next(3);
            if (Enum.IsDefined(typeof(Test), value))
                return (Test)value;

            return null;
        }
    }

    public enum Test
    {
        Foo = 1,

        Bar = 2,
    }
}

Expected Behavior:
IDE0004 should not report on line int? testId = should ? (int?)test : null; because the explicit cast is indeed required.

Actual Behavior:
IDE0004 incorrectly reports on the relevant line (the codefix preview even shows that applying the "fix" will cause a compile error):

image

Question/Suggestion:

If the IDE detects that a codefix it's suggested would generate un-compilable code, would it make sense (a) for the IDE to suppress that codefix (and possibly the associated analyzer) (b) report this to Microsoft via telemetry?

Metadata

Metadata

Labels

Area-IDEuntriagedIssues and PRs which have not yet been triaged by a lead

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions