Odd behavior when passing nullable value types as parameter
#60,683 opened on Apr 11, 2022
Repository metrics
- Stars
- (20,414 stars)
- PR merge metrics
- (Avg merge 6d 17h) (256 merged PRs in 30d)
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.