How to deal with "List<T>.Add(default)" correctly?

Viewed 195

Consider the following code compiled in a #nullable context and using .Net Framework 4.8:

public sealed class Test<T>
{
    public Test()
    {
        _data.Add(default); // warning CS8604: Possible null reference argument for parameter 'item' in 'void List<T>.Add(T item)'.
    }

    public T Item => _data[0];

    readonly List<T> _data = new List<T>();
}

This code causes Warning CS8604, as indicated by the comment.

It is not possible to fix the code by using T? without constraining T to be class:

public sealed class Test<T>
{
    public Test()
    {
        _data.Add(default);
    }

    public T? Item => _data[0];                // error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type

    readonly List<T?> _data = new List<T?>();  // error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type
}

I cannot add a "struct" or "class" type constraint because this code is actually in a PriorityQueue<T> class that is already used in a lot of places with both value and reference types.

So what I've done for now is just suppress the message like so:

public Test()
{
    _data.Add(default!); // Note the "!"
}

Is this the correct way to handle this (given that this has to work with .Net Framework 4.8, so the new null-related code annotations are not available)?

0 Answers
Related