3

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

var email = (User user = User.Current) != null ? user.Email : "default@mail.com";

When this is allowed:

User user;
var email = (user = User.Current) != null ? user.Email : "default@mail.com";

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 : "default@mail.com";

could be

var email = (var user = User.Current.Very.Complex.Path) != null ? user.Email : "default@mail.com";
4

1 回答 1

3

根据 C# 规范,不允许您尝试做的事情。这基本上是因为变量声明/初始化是一个语句,而不是一个表达式(有关更多详细信息,请参阅为什么我们不能在 if 语句中定义变量?感谢Pierre-Luc Pineault的链接)。

这是另一种方法,我认为它具有很高的可读性和简洁性:

var user = User.Current.Very.Complex.Path;
var email = user != null ? user.Email : "default@mail.com";
于 2013-08-27T13:55:46.663 回答