C#C
C#4y ago
Anton

Nullability in an assertion checking method [Answered]

I have a piece of code that checks for nulls in another method, then proceeds to use the values as if they weren't null. How do I annotate the checking method such that the compiler knows that after I've called it, the values are never null?
class Whatever
{
    private int[]? _arrayRef;
    public struct DrawPosition
    {
        public int Top;
        public int Left;
    }
    public DrawPosition? Position { get; set; }

    private void AssertInitialized()
    {
        Debug.Assert(_arrayRef is not null);
        Debug.Assert(Position.HasValue);
    }

    public void BeginSwap(int index0, int index1)
    {
        AssertInitialized();
        // The compiler complains that Position might be null.
        DrawState(Position.Value, _cachedElementWidth, _arrayRef);
    }
}
Was this page helpful?