1

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?

Stefan
  • 17,448
  • 11
  • 60
  • 79
OwnageIsMagic
  • 1,949
  • 1
  • 16
  • 31
  • Can you give an example of `T`? – Stefan Oct 10 '20 at 17:54
  • @Stefan This is not allowed syntax in c#. I used it to just show function signature. For example `T is List<> and TT is object --> T is List` – OwnageIsMagic Oct 10 '20 at 17:58
  • 1
    https://stackoverflow.com/q/58569906/11683, which points to https://devblogs.microsoft.com/dotnet/try-out-nullable-reference-types/#the-issue-with-t? – GSerg Oct 10 '20 at 18:26
  • @GSerg more I think about this, more I understand, that this question is about limitation of generics int C#. There is now way to express functions that operate on types at compile time. Like `??? CretateWith ()` ; `List a = CreateWith, int>()` – OwnageIsMagic Oct 10 '20 at 18:57

1 Answers1

0

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
OwnageIsMagic
  • 1,949
  • 1
  • 16
  • 31