newclearwinter
newclearwinter

Reputation: 1073

Is there a way to indicate to C# nullability analysis that an instance variable will never be null after a certain method runs?

I've got a class with an instance var that can be null, and that class has a method that initializes that var. Broadly simplified, it looks a bit like this

#nullable enable

class SomeClass
{
    private Foo? someObject;

    private void InitSomeObject()
    {
        someObject = new Foo() { ... }
    }

    public SomeMethod()
    {
        if (someObject?.Id == null)
            InitSomeObject();

        Console.WriteLine(someObject.Id) // <-- nullability warning here, "someObject may be null"
    }
}

Is there a way to indicate to the compiler that someObject is not null once InitSomeObject() has been called?

Upvotes: 0

Views: 42

Answers (1)

tire0011
tire0011

Reputation: 1058

Hm...

maybe not the answer what you want or...

Why you not remove the nullable from Foo and initalize it with FooEmpty?

class FooEmpty : Foo
{

}

class SomeClass
{
    private Foo someObject = new FooEmpty(); // better singelton

    private void InitSomeObject()
    {
        someObject = new Foo() { ... }
    }

    public SomeMethod()
    {
        if (someObject is FooEmpty)
            InitSomeObject();

        Console.WriteLine(someObject.Id) 
    }
}

or you have a Empty Flag in Foo itself

class Foo
{

   public bool IsEmpty => SomeProperty == false && StringFoo == string.Empty;
}

class SomeClass
{
    private Foo someObject = new Foo(); // better singelton

    private void InitSomeObject()
    {
        someObject = new Foo() { ... }
    }

    public SomeMethod()
    {
        if (someObject.IsEmpty)
            InitSomeObject();

        Console.WriteLine(someObject.Id) 
    }
}

Upvotes: 0

Related Questions