简体   繁体   中英

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 xy 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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM