Djoums
Djoums

Reputation: 33

Nullable enable with collection of T

I'm currently working on enabling the nullable option on one of our company projects, and I'm not sure how to handle the following situation.

public class MyCollection<T>
{
    private T[] myArray;
    public T this[int i]
    {
        get => myArray[i];
        set => myArray[i] = value;
    }
}

If T is a reference type, I want null to be a valid value. But in case of a value type, I don't want Nullable<T> to be involved, keep the type as is.

I tried playing with annotations, but in the end if value can be null in the setter, I'm forced to declare myArray as a T?[].

public class MyCollection<T>
{
    private T[];
    [AllowNull]
    public T this[int i]
    {
        [return: MaybeNull]
        get => myArray[i];
        set => myArray[i] = value; // Possibly null
    }
}

So I guess my questions are :

Upvotes: 3

Views: 427

Answers (1)

Drew Noakes
Drew Noakes

Reputation: 310997

In C# 9 you can apply ? to an "unconstrained generic type" and it won't produce Nullable<T> if T is a struct.

So your example becomes:

public class MyCollection<T>
{
    private T?[] myArray;
    public T? this[int i]
    {
        get => myArray[i];
        set => myArray[i] = value;
    }
}

The attributes work too, but are less elegant.

Upvotes: 3

Related Questions