dotnet/roslyn

Odd behavior when passing nullable value types as parameter

Open

#60 683 ouverte le 11 avr. 2022

Voir sur GitHub
 (2 commentaires) (0 réactions) (0 assignés)C# (4 257 forks)batch import
Area-InteractiveBughelp wanted

Métriques du dépôt

Stars
 (20 414 stars)
Métriques de merge PR
 (Merge moyen 6j 17h) (256 PRs mergées en 30 j)

Description

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.

Guide contributeur