Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# if statement. inner workings Q

Tags:

c#

I've just come across this code snippet in some Exchange 2010 code and I was wondering if anyone knew why the programmer has done it this way. I've never seen an If statement formatted like this. It seems so backwards there must be a good reason for it??

if (true == MsgItem.HasAttachments)
{
    // Code
}

I'm assuming it might have some optimisation over the various other ways of coding the same thing;

if (MsgItem.HasAttachments) 
{
    // Code
}

or

if (MsgItem.HasAttachments == true)
{
    // Code
}

Its not a big deal I'm just curious.

Thanks, Mike

UPDATE: Thanks for all the interesting points raised. Summary seems to be it's down to legacy coding standards.

like image 545
Mike Mengell Avatar asked May 27 '10 14:05

Mike Mengell


2 Answers

It is a left-over habit from C or C++ where you might accidentally do:

if (i = 1) {
}

This accidentally assigns 1 to i instead of doing a comparison.

Reversing the order in the check prevents this common mistake.

if (1 = i) {
}

That will not compile, and it is easy to see that you mistakenly typed = instead of ==.

This is still relevant for bools in C# because the value of an assignment is the value that was assigned.

Therefor:

if (SomeBoolVar = true) {
}

Will always be true because you are storing true into SomeBoolVar which evaluates to true. A little mistake that can be hard to track down.

like image 178
jjnguy Avatar answered Oct 23 '22 11:10

jjnguy


C++ and C programmers sometimes put constants first, to avoid accidentally writing

if (variable = constant)

which would perform an assignment.

In particular, explicitly for boolean comparisons, assuming HasAttachments is writable, this statement would compile and run with no warnings1, but not have the intended behaviour in C#:

if (MsgItem.HasAttachments = true)

For non-Boolean expressions, this isn't usually an issue in C# because the condition of an if statement has to be implicitly convertible to bool... and for Boolean expressions, your middle form is preferred anyway:

if (MsgItem.HasAttachments)

I would be amazed if it had any performance impact at all - and probably no impact on the generated IL to start with.


1 Oops - the MS C# compiler does indeed warn for this:

warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ?

I haven't tried it under Mono though; that may or may not give a warning. It's certainly valid C# code.

like image 36
Jon Skeet Avatar answered Oct 23 '22 11:10

Jon Skeet