Is there a way to inform the code analyzer that a nullable property of a returned object is not null, particularly when the object is created by a different class? For example, consider the following scenario:
class Foo {
public string? Name { get;set; }
}
class Bar {
// what attribute to use here?
Foo CreateFoo() {
return new Foo { Name = "123" };
}
}
Is there an attribute that can be used to indicate to the code analyzer that any Foo object created by Bar.CreateFoo() will always have a non-null Foo.Name property?
I create an example that will show Converting null literal or possible null value to non-nullable type
warning and here’s the example:
var bar = new Bar();
Foo foo = bar.CreateFoo();
string text = foo.Name; // "Name" may be null.
class Foo {
public string? Name { get;set; }
}
class Bar {
public Foo CreateFoo() {
return new Foo { Name = "123" };
}
}
If you are sure Name
will not be null at that line. You can use null-forgiving operator !
to tell analyzer it is not null. Like this:
string text = foo.Name!;
More about null-forgiving operator | microsoft.com