Are these two lines the same, '? … :' vs &

2020-05-14 04:45发布

Is there a difference between these two lines?

MyName = (s.MyName == null) ? string.Empty : s.MyName

or

MyName = s.MyName ?? string.Empty

标签: c#
7条回答
一纸荒年 Trace。
2楼-- · 2020-05-14 05:25

The only difference is whether you evaluate s.MyName twice or once. The first will do it twice in the case that s.MyName is not null, the second will only ever evaluate it once.

In most cases, this difference doesn't matter, and I'd go with the second because it's more clear and concise.

查看更多
登录 后发表回答