How can I tell Visual Studio IntelliSense that property of property is not null after calling its method
Inner class:
class Inner
{
int? Property { get; set; }
[MemberNotNull(nameof(Property))]
void Initialize
{
Property = 42;
}
}
Caller class:
class Caller
{
// We know here that constructor is always called before other methods
public Caller()
{
InnerObj = new Inner();
// We know here that InnerObj.Property is always not null
InnerObj.Initialize();
}
public Inner InnerObj { get; }
public void MethodWithNullWarning()
{
// Null Warning
InnerObj.Property.ToString();
}
}
CodePudding user response:
You can use the null-forgiving operator.
InnerObj!.Property.ToString();
Quoted from docs:
Available in C# 8.0 and later, the unary postfix ! operator is the null-forgiving, or null-suppression, operator. In an enabled nullable annotation context, you use the null-forgiving operator to declare that expression x of a reference type isn't null: x!. The unary prefix ! operator is the logical negation operator.
CodePudding user response:
Assigning the property in the constructor doesn't guarantee it will not be null.
Let's add the following method:
public void MakeItNull() { InnerObj.Property = null; }
Then:
Caller caller = new ();
caller.MakeItNull();
caller.MethodWithNullWarning();
Boom!
Solutions
Here are some options.
1. !
! (null-forgiving) operator (C# reference)
InnerObj.Property!.ToString();
Please note that this doesn't protect from a null reference exception if the value is actually null.
2. Have a constructor
class Inner
{
public string Property { get; set; } // string, not string!
public Inner() {
Property = "42";
}
}
3. Use a different property for external access.
class Inner
{
private string? RealProperty { get; set; }
public string Property => RealProperty!;
public void Initialize() {
RealProperty = "42";
}
}