dotnet/roslyn

Odd behavior when passing nullable value types as parameter

Open

#60.683 geöffnet am 11. Apr. 2022

Auf GitHub ansehen
 (2 Kommentare) (0 Reaktionen) (0 zugewiesene Personen)C# (4.257 Forks)batch import
Area-InteractiveBughelp wanted

Repository-Metriken

Stars
 (20.414 Stars)
PR-Merge-Metriken
 (Durchschn. Merge 6T 17h) (256 gemergte PRs in 30 T)

Beschreibung

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.

Contributor Guide