C# Nullable attribute - generic array items

Viewed 271

Note: I am using C# 8's Nullable Reference Types. Reference types are, by default NOT nullable.

Suppose I have the following method:

public void TestMethod<T>(T[] items)
{

}

Without using any generic constraints, how can I use the Nullable attributes to specify that the array itself will not be null, but an individual item in the array may be null?

My goal is the following:

  • No warning, due to the array itself being not null: var len = items.Length;
  • Warning, because an individual item can be null: items[0].ToString()
  • No warning, because of the null coalescing operator: items[0]?.ToString()

This code seems to indicate that the array itself can be null, but, if the array itself is not-null, then each array item is also not null:

public void TestMethod<T>([MaybeNull]T[] items)
{

}

I know that using generic constraints will solve this problem - because I could then use T?[] items - but, then I have to create two versions of the class - one for value types and one for reference types. Is there a way to indicate this without using generic constraints?

0 Answers
Related