Nullability attributes on type parameter (C#)

330 Views Asked by At

From docs the main reason for [AllowNull] attribute is to apply it to generics, where T? syntax can't be used. But AllowNull is not allowed to be specified on generic parameters.

void f<[AllowNull] T>() {} // error

Is there any way to make function like this?

[return: NotNull]
T<TT> HasNoNulls<T, [NotNull] TT>(T<TT?>? val)

UPDATE: I get it why this is not allowed. Because null analysis is tied to data flow it only allowed on variables. How to solve this nested generic problem?

1

There are 1 best solutions below

0
On

Closest thing I get is

   [return: NotNullPost]
    public static T HasNoNulls<T, TT>([NotNullPost][AllowNull] T value)
        where T : IEnumerable<TT>
    {
        if (value.Any(e => e is null))
            throw new ArgumentException();
        return value;
    }

List<string?>? list = null;
// requires to specify types and use null assertion ↓
var ll = Check.HasNoNulls<List<string>, string>(list!, "");
ll[0].Trim(); // no warnings