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

[Feature Request] var pattern in IF statement while making null check #2102

Closed
webwarrior06 opened this issue Dec 24, 2018 · 6 comments
Closed

Comments

@webwarrior06
Copy link

webwarrior06 commented Dec 24, 2018

Wouldn't it be better if we can create a variable inside IF statement if checked value is not null, like we have in type checking with "is";

To make it clear;

if(Long.Named.Method.Chain.Or.Static.Etc.Value != null var x){

   //...things related to x variable

}

Otherwise, It has to be a variable defined before the IF statement in order not to write long-character variable over and over again. Like this;

var x = Long.Named.Method.Chain.Or.Static.Etc.Value;
if(x != null){

}
@DavidArno
Copy link

DavidArno commented Dec 24, 2018

With C# 8, you can do this with the {} pattern:

if(Long.Named.Method.Chain.Or.Static.Etc.Value is {} x)

EDIT

Ah, I see @ufcpp already posted a code example showing this in action 😃

@webwarrior06
Copy link
Author

Thanks for the info guys. I could not realized something similar was proposed before. 😊
It will be very useful. 👍

@pinkfloydx33
Copy link

Can't you already do the following with C#7 (sure, a bit more verbose)?
if(Long.Named.Method.Chain.Or.Static.Etc.Value is var x && x != null) ...

If you know the type, then it's practically the same (but sure, not var)
if(Long.Named.Method.Chain.Or.Static.Etc.Value is SomeType x) ...

@webwarrior06
Copy link
Author

webwarrior06 commented Dec 24, 2018

@pinkfloydx33 Yeah, the first one is sort of verbose. In fact, the second is better and easy to use for now. We will have this problem solved totally with C# 8 as in @DavidArno's post.

@Joe4evr
Copy link
Contributor

Joe4evr commented Dec 25, 2018

Please close, then.

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