Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Generic class: infer non-nullable type from nullable type parameter

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;
}
like image 927
Liero Avatar asked Nov 05 '20 07:11

Liero


Video Answer


1 Answers

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.
like image 95
Yair Halberstadt Avatar answered Oct 20 '22 20:10

Yair Halberstadt