-
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
Use an ! operator to assert that a variable is not null. #3096
Comments
We considered something like this for the initial version of C# 8: #1865. We decided against this, and at this point this would be a breaking change. |
Breaking change can be avoided by introducing a new string? s = null;
string t = s!!; // throws NullReferenceException |
@ronnygunawan yes, but note that your example uses reference types and the issue is about nullable value types. |
@333fred I was actually talking about both reference types and nullable value types; sorry if I wasn't clear! |
For nullable value type: int? i = null;
int j = i!!; // equivalent to i!.Value, throws InvalidOperationException: Nullable object must have a value. |
This feature would make using nullables so much cleaner and easier. I run into issues whenever I'm dealing with deserialized data. The models' types are all nullable and I end up having to litter my code with explicit null checks. I've taken to adding the following two extension methods to all my projects to make it slightly cleaner: public static T GetValue<T>(this T? possibleNull, [CallerLineNumber] int sourceLineNumber = 0) where T : class =>
possibleNull ?? throw new NullReferenceException($"Value is null on line {sourceLineNumber}");
public static T GetValue<T>(this T? possibleNull, [CallerLineNumber] int sourceLineNumber = 0) where T : struct =>
possibleNull ?? throw new NullReferenceException($"Value is null on line {sourceLineNumber}"); The new |
Closing as the feature as suggested here is a breaking change |
This would be useful to simplify conversion of nullable types to non-nullable types:
The text was updated successfully, but these errors were encountered: