Skip to content
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

Closed
ekolis opened this issue Jan 13, 2020 · 7 comments
Closed

Use an ! operator to assert that a variable is not null. #3096

ekolis opened this issue Jan 13, 2020 · 7 comments

Comments

@ekolis
Copy link

ekolis commented Jan 13, 2020

This would be useful to simplify conversion of nullable types to non-nullable types:

int? answer = 42;
int magic = answer!; // equivalent to answer.Value or (int)answer
@333fred
Copy link
Member

333fred commented Jan 13, 2020

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.

@ronnygunawan
Copy link

Breaking change can be avoided by introducing a new !! operator.

string? s = null;
string t = s!!; // throws NullReferenceException

@333fred
Copy link
Member

333fred commented Jan 14, 2020

@ronnygunawan yes, but note that your example uses reference types and the issue is about nullable value types.

@ekolis
Copy link
Author

ekolis commented Jan 14, 2020

@333fred I was actually talking about both reference types and nullable value types; sorry if I wasn't clear!

@ronnygunawan
Copy link

For nullable value type:

int? i = null;
int j = i!!; // equivalent to i!.Value, throws InvalidOperationException: Nullable object must have a value.

@MatisseHack
Copy link

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 CallerArgumentExpression proposal would improve the exception message, but this is better than nothing. I would love to have a language feature to do this assertion more concisely!

@YairHalberstadt
Copy link
Contributor

Closing as the feature as suggested here is a breaking change

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants