hultqvist
hultqvist

Reputation: 18471

Testing for null without affecting C# 8 nullable analyzer

With C# 8 nullable enabled, the following code generates no errors.

var x = GetObjectX();
return x;

By adding one line I get a warning:

var x = GetObjectX();
Debug.Assert(x != null);
return x; //Warning: 'X' may be null here. Possible null reference return.

Is this an expected behavior?

The reason I don't trust the nullable algorithm without the Debug line is because the object returned is deserialized.

What's the cleanest way to suppress the warning?

Upvotes: 5

Views: 1264

Answers (2)

Julien Couvreur
Julien Couvreur

Reputation: 4983

In .NET Core 3, Debug.Assert is annotated with [DoesNotReturnWhen(false)], which helps the compile understand the code and avoid the warning.

Without it, the compiler sees the null test as an indication from the user that the value could have been null after all.

You can make your own assertion method if you’re not using .NET Core 3. See RoslynDebug.Assert as an example.

Upvotes: 5

Rodrigo Rodrigues
Rodrigo Rodrigues

Reputation: 8576

Try the null forgiving operator ! It can be used when you know, better than the compiler, that a nullable variable will not be null at runtime.

var x = GetObjectX();
Debug.Assert(x != null);
return x!;

Upvotes: 5

Related Questions