-
Notifications
You must be signed in to change notification settings - Fork 1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Non-null test operator ? #2634
Comments
if (myNullableObj is null)
{
// Null here.
}
if (myNullableObj is object)
{
// Not null here.
} I think how you propose to check for null is confusing because the important parts of the syntax are at both ends of the variable. |
If it's confusing at the end of the variable, I'm all for putting it at the beginning of the variable instead: |
If I saw that syntax in someone else's code, I would have no idea what it meant. Add to that the fact that you're only saving a few characters... |
@canton7 In my view, it feels like asking a question in a 'if' statement. It somewhat reads as follow: |
A non-null check operator has already been suggested and discussed.
I still think it would be nice to have such a non-null check operator in C#, because it allows shorter checks (like in C and C++), but without the problems of auto-conversion to bool. |
@MillKaDe Exactly! It's a shame that all the threads you linked are closed issues... :( |
I think that a non-null test operator (?) should be introduced. This would simply be a test for a non-null value of a class type. It would basically check the reference and convert it into a boolean 'true' if non-null.
bool nonNull = myNullableObj?;
So instead of doing this to test for non-null:
if ( myNullableObj != null ) { ... }
You could simply do this:
if ( myNullableObj? ) { ... }
Simple, elegant and it fits naturally in the spirit of the the null conditional (?.) and null coalescing ()?? operators.
Also, instead of testing for null like this:
if ( myNullableObj == null ) { ... }
You should be able to do this:
if ( !myNullableObj? ) { ... }
I think that it's probably simple enough to implement in the language since the ?. operator already does something similar internally anyway.
Of course, there could be a little challenge to properly distinguish it from the ( ? : ) statement. But I think the solution for this is simple: if the left-operand is a nullable type, then the middle and right operands along with the ':' must not be present.
The text was updated successfully, but these errors were encountered: