digitig
digitig

Reputation: 2140

Why am I getting warning that a non-nullable field must be initialised (When I'm sure I'm initialising it)?

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?

Upvotes: 8

Views: 1251

Answers (1)

K. L.
K. L.

Reputation: 261

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.

Upvotes: 10

Related Questions