5

I use C# 8 nullable reference types.

I have a generic class that might accept nullable reference type as a type parameter.

Is there a way to declare non-nullable type based on generic type parameter that might be nullable reference type (or even Nullable struct)?

abstract class Selector<T>
{
    T SelectedItem;

    // how to make item parameter not nullable?
    abstract string Format(T! item);

    // how to make item parameter not nullable?
    Func<T!, string> FormatFunction;
}
Liero
  • 25,216
  • 29
  • 151
  • 297
  • 3
    You should look into using the attributes instead of the `!` and `?` symbols to denote nullability. Since nullable value types and reference types are implemented completely different, there is no easy common way to deal with both. – Lasse V. Karlsen Nov 05 '20 at 07:58

1 Answers1

5

Use DisallowNullAttribute:

using System.Diagnostics.CodeAnalysis;

abstract class Selector<T>
{
    T SelectedItem;

    public abstract string Format([DisallowNull] T item);
}

var selector = default(Selector<string?>)!;
selector.Format(null); //warning CS8625: Cannot convert null literal to non-nullable reference type.
Yair Halberstadt
  • 5,733
  • 28
  • 60