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.