dotnet/roslyn

Odd behavior when passing nullable value types as parameter

Open

#60.683 aperta il 11 apr 2022

Vedi su GitHub
 (2 commenti) (0 reazioni) (0 assegnatari)C# (4257 fork)batch import
Area-InteractiveBughelp wanted

Metriche repository

Star
 (20.414 star)
Metriche merge PR
 (Merge medio 6g 17h) (256 PR mergiate in 30 g)

Descrizione

Visual Studio 2022 17.2.0 Preview 2.1

using System;

namespace Test
{
    public class Program
    {
        public static void Main ()
        {
            var model = new Model();

            Console.WriteLine(GetInt(model.Id));
        }

        static int GetInt (int value)
        {
            return value;
        }

        static int GetInt ( int? value )
        {
            //Error in immediate window
            //if (value is int x)
            //    return x;

            return value.GetValueOrDefault();
        }
    }

    public class Model
    {
        public int? Id { get; set; }
    }
}

The above code is a subset of code that I have in an app. At runtime my app was crashing with a NullReferenceException. I was passing null as the parameter value and seeing a crash so I went to the debugger to diagnose.

Expected Behavior:

Debugger should not generate error when evaluating value is int x.

Actual Behavior:

When setting a breakpoint in the GetInt function and then using the immediate window to evaluate value is int x I get an error Internal error in C# compiler. However if you uncomment the code in the function then it correctly evaluates the if statement.

The net result is that functions accepting a nullable int do not behavior consistently between the debugger and runtime when the value is null.

Guida contributor