Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using FluentAssertions NotBeNull isn't taken into account by nullable analysers

When I use Fluent assertions to test if a property is not null, the analysers still complain about subsequent lines which dereference that line as possibly null. Is there any way to get the compiler to recognise the property as not being null after testing with FluentAssertions? e.g.

Foo? foo = Bar();

foo.Should().NotBeNull();
foo.Value.Should().Be(5); // Warning about dereference of a possibly null reference on this line

I know I can use a ! on the foo in the second line but is there any way to get the analysers to work this out for itself?

I did find this but I can't see how it can be used in this case.

like image 836
Mog0 Avatar asked Jan 30 '26 02:01

Mog0


1 Answers

You could write your own alternative extension method:

public static void ShouldNotBeNull<T>([NotNull] this T? value)
{
  // throw if null
}
like image 176
Drew Noakes Avatar answered Jan 31 '26 19:01

Drew Noakes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!