Reputation: 1073
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
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