Home > Net >  Why am I getting warning that a non-nullable field must be initialised (When I'm sure I'm
Why am I getting warning that a non-nullable field must be initialised (When I'm sure I'm

Time:12-01

I have:

public abstract class Craft
{
    public Craft()
    {
        CurrentQuadrant = new Point(0, 0);
    }

    private Point _currentQuadrant;
    public Point CurrentQuadrant
    {
        get => _currentQuadrant;
        set
        {
            _currentQuadrant = value;
        }
    }
}

(Point is a simple x-y pair).

Why would that be giving me the warning that Non-nullable field '_currentQuadrant' must contain a non-null value when exiting the constructor? Doesn't the assignment make sure it's non-null?

CodePudding user response:

Too little reputation to comment, so I'll post it here.

If you're using .NET 5 , you can use the [MemberNotNull] attribute (more info here).

Just put [MemberNotNull(nameof(_currentQuadrant)] on your constructor and the warning will disappear.

Or you could just assign the value to _currentQuadrant instead of CurrentQuadrant.

  • Related