I am a big fan of C# nullable references and we enable them in all our new projects. Recently I was reviewing a PR from a co-worker and found that [Optional] attribute was used next to the reference parameter with no default value being specified. This would mean that we are breaking "nullable reference constraint" as the default value for the function argument would be null, even though the argument is not marked as nullable. Please see the example code below:
class Program
{
internal class Data
{
internal int Count { get; set; } = 3;
}
static void Main(string[] args)
{
BadUse();
GoodUse();
}
static void BadUse([Optional] Data data) => Console.WriteLine($"Data: ${data.Count}");
static void BadUse2([Optional, DefaultParameterValue(null)] Data data) => Console.WriteLine($"Data: ${data.Count}");
static void GoodUse(Data? data = null) => Console.WriteLine($"Data: ${data?.Count}");
}
As you can see the method BadUse above is incorrect and will cause null reference exception without any warning nor compilation error. Naturally, we use the more readable optional argument pattern as in GoodUse. I wonder if this is a bug in C# compiler or I am missing something here? I would expect to see compilation error or at least some warning.
Note that when the DefaultParameterValue attribute is used in BadUse2 we get the expected "CS8602 Dereference of a possibly null reference".