Feature suggestion: new nullability attribute: NotNullWhenMethodReturnsSuccessfully #4127
-
A lot of unit test assertion libraries have methods such as: void AssertNotNull(string? variableToTest)
{
// will throw if variableToTest is null
} But unfortunately there's no way for these libraries to let the static flow analysis know that it won't be null if the method returns without throwing, since no such attribute exists. Here's an example using FluentAssertions, one of the most popular assertion libraries for C#: Would it be possible to add a new nullability attribute that tells the compiler that an argument will not be null, if the method returns successfully? Maybe something like |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Well, the original example could just be defined as: void AssertNotNull([NotNull] string? variableToTest)
{
// will throw if variableToTest is null
} This would provide exactly the semantics you want. The second example, though, I'm not sure is possible. You'd need to have the results of a second method somehow passing through inference to the parameter of the first method, and I'm not really sure there's a way to do this. Maybe a particularly specialized attribute could do this, but I don't know how that could be generally-applicable enough to be worth adding to the language. |
Beta Was this translation helpful? Give feedback.
Well, the original example could just be defined as:
This would provide exactly the semantics you want.
The second example, though, I'm not sure is possible. You'd need to have the results of a second method somehow passing through inference to the parameter of the first method, and I'm not really sure there's a way to do this. Maybe a particularly specialized attribute could do this, but I don't know how that could be generally-applicable enough to be worth adding to the language.