Reputation: 48
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();
}
}
Upvotes: 0
Views: 638
Reputation: 35115
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!
Here are some options.
! (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.
class Inner
{
public string Property { get; set; } // string, not string!
public Inner() {
Property = "42";
}
}
class Inner
{
private string? RealProperty { get; set; }
public string Property => RealProperty!;
public void Initialize() {
RealProperty = "42";
}
}
Upvotes: 0