© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
4 replies
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);
    }
}
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Nullability issue
C#CC# / help
3y ago
Confusion with nullability of a custom LINQ method
C#CC# / help
5mo ago
Puzzled about Nullability in EFCore
C#CC# / help
14mo ago
❔ EF Core nullability vs API nullability behavior
C#CC# / help
4y ago