C
C#3y 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);
}
}
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);
}
}
4 Replies
333fred
333fred3y ago
[MemberNotNull(nameof(_arrayRef))]
[MemberNotNull(nameof(Position))]
private void AssertInitialized()
{
Debug.Assert(_arrayRef is not null);
Debug.Assert(Position.HasValue);
}
[MemberNotNull(nameof(_arrayRef))]
[MemberNotNull(nameof(Position))]
private void AssertInitialized()
{
Debug.Assert(_arrayRef is not null);
Debug.Assert(Position.HasValue);
}
Anton
AntonOP3y ago
Thank you
333fred
333fred3y ago
yw
Accord
Accord3y ago
✅ This post has been marked as answered!

Did you find this page helpful?