Declare variable in one line if statement [duplicate]
Asked Answered
Q

1

3

I wonder why this syntax is not allowed in c#?

var email = (User user = User.Current) != null ? user.Email : "[email protected]";

When this is allowed:

User user;
var email = (user = User.Current) != null ? user.Email : "[email protected]";

Why does the variable have to be defined already, and cannot be defined in the statement?

This would help to make lines shorter, for example:

var email = User.Current.Very.Complex.Path != null ? User.Current.Very.Complex.Path.Email : "[email protected]";

could be

var email = (var user = User.Current.Very.Complex.Path) != null ? user.Email : "[email protected]";
Quiteri answered 27/8, 2013 at 13:42 Comment(8)
This is due to the scope/encapsulation. If you declare the variable in the ternary, it's only available within it and I suspect the compiler guesses this is a fault. Also, some times, having a few more lines is better than 1 if it improves readability. Personally, I'd rather this split over a few lines, but each to their own here!Broke
Is () a scope? I thought this could work like a can be used in using(var a = GetVar()){ /*use a*/}. Ie: variables declared in one line if's can be used in the rest of the statement.Quiteri
Please see this questionKalynkam
@Pierre-LucPineault Ah, this seems like the answer!Quiteri
IMHO doing that would decrease readability, why don't you want to just do the 2nd block? Your final example could just be turned in to User user; var email = (user = User.Current.Very.Complex.Path) != null ? user.Email : "[email protected]";Sausage
I can't see it at the moment, but it seems like the null-coalescing operator (??) should be able to help you out here. Maybe you need a default user instance somewhere.Novel
@JoelCoehoorn Unfortunately not without having to constructing a new User: var email = (User.Current ?? new User { Email = "[email protected]" }).Email;Quiteri
@ScottChamberlain, apparently the c# team disagrees. Declaration Expressions almost made it into c# 6.0 and will make it into a future release sooner or later.Toucan
B
3

What you're trying to do is not allowed, per the C# specification. This is basically because a variable declaration/initialization is a statement, not an expression (see Why can't we define a variable inside an if statement? for more details; credit to Pierre-Luc Pineault for linking that).

Here is another way to do it, which I think has high readability and conciseness:

var user = User.Current.Very.Complex.Path;
var email = user != null ? user.Email : "[email protected]";
Barnaul answered 27/8, 2013 at 13:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.