Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Satisfy or silence nullable generic type property warning

Using nullable reference types in C#8.0, given this simplified code, where T can be any value type or reference type, and where null values are valid values of reference type T instances:

public class C<T>
{
    public T P { get; set; }
}

the compiler issues warning CS8618 "Non-nullable property 'P' is uninitialized. Consider declaring the property as nullable.". How can I satisfy the compiler and silence this warning (without suppressing CS8618)?

Is there an attribute, or a type parameter constraint that I can apply? In that case how?

The best I've come up with is

public T P { get; set; } = default!;

but I'm hoping for a way to do it without using the null-forgiving/"dammit" operator ('!').

Note: You cannot declare the type of the property as T? - CS8627. Besides, that would imply that any value type returned would be Nullable<T>, which is not what is intended. (Read more about this e.g. here.)


Edit: I notice this also works:

public class C<T>
{
    public C()
    {
        P = default;
    }
    [AllowNull]
    public T P { get; set; }
}

However I would have prefered to use an auto-property initializer.

like image 331
Ulf Åkerstedt Avatar asked Nov 07 '22 11:11

Ulf Åkerstedt


1 Answers

Basically, class and struct nullability are simply incompatible and cannot be combined.

Your options include:

  • Keep your class completely generic; so, no differentiating within your class between T and T?. This does still allow for C<int> and C<int?>, just not T?.

  • Constrain either to class or struct, depending on your requirements.

  • Write two separate classes, one for structs one for reference types.

It's not that bad to write two classes if they're simple enough. You might be able to push the non-generic parts into a base class to avoid too much repetition.

like image 101
Dave Cousineau Avatar answered Nov 12 '22 19:11

Dave Cousineau