"Strange" C# syntax
I just saw this in a project I downloaded from Code Project:
base.DialogResult = this.Result != null;
I don't consider myself new to C# but this one is new to me. Can anyon开发者_Python百科e tell me what's going on with this statement?
Edit Great answers, thanks. I've just never used that before.
If you add parens it's easier to read (and understand). The logical comparison operator !=
precedes the assignment operator =
:
base.DialogResult = (this.Result != null);
The same statement, even more verbose:
if (this.Result != null)
base.DialogResult = true;
else
base.DialogResult = false;
this.Result != null
evaluates to a boolean, true
or false
.
The result of the evaluation is set in the DialogResult
member of the base class.
Not strange at all, it's just an assignment.
The !=
(not equal) operator has precedence over the =
(assignment) operator.
Thats simple, basically it assigns the result of the expression
this.Result != null
to
base.DialogResult
the expression uses the in-equality operator, so it returns either true or false, depending on wether this.Result is null or not
That means:
bool g = (this.Result != null);
this.DialogResult = g;
精彩评论