C# bool expression evaluation order [duplicate] - c#

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
== Operator and operands
Possible Duplicates:
Is there any difference between if(a==5) or if(5==a) in C#?
== Operator and operands
Ok, this may be stupid question, but searching in google (cant seem to ACTUALLY search for an exact phrase even with quotes)
What if any difference is there between
if(false == <somecondition>){
and
if(<somecondition> == false){
in C#? I am familiar with c#'s expression evalution, and understand how the order would make sense if you were doing something like:
if(AccountIsInvalid || AccountIsUnregistered)
I dont need a huge lesson, but would like to understand why some people prefer to do things with false==.... route.

Personally, I never compare anything to false or true.
I would go with:
if (!somecondition)
or:
if (somecondition)

In C there would have been, perhaps, some reason to do this as you could easily make a mistake and use the assignment operator instead of the comparison operator, but in C# it shouldn't make any difference -- you'll get a compile warning if you use the assignment operator. If the assignment were a different type (say int), it would result in an error, since the result wouldn't be a legal expression for the if statement.
I would prefer it to be
if (!<somecondition>)
{
...
}
rather than a comparison to false (or true, for that matter).

Before performing any optimizations or short-circuits, the compiler needs to resolve <somecondition> to true or false value, thus there is no reason why the compiler would evaluate the expressions <somecondition> == false and false == <somecondition> any differently.
This must surely be an issue of style, and style only.

This doesn't matter in C# like it does in c/c++ because conditions must evaluate to a boolean.

Related

C# - Why doesn't Object class have true operator?

Sorry if my question seem stupid.
In C++, this code work:
Foo* foo = new Foo();
if (foo)
....;
else
....;
In C#, this doesn't work:
Object obj = new Object();
if (obj)
....;
else
....;
because Object class cannot be implicitly convert to bool (obvious, no problem about that), and it doesn't implement true operator.
So my question is why doesn't Object implement the true operator (just check whether itself is null or not, sound easy enough)? Is it just because of code readability or something?
It's because of code clarity. A lot of design choices for C# were made with the goal that the code should be written in such a way that it is immediately obvious what it is trying to do. If you have something like:
Object obj = ...;
if (obj)
....
What does if(obj) mean? Is it checking if obj true? Is it checking if it is null? Is it checking if it is 0? It's not clear to someone glancing at the code and necessitates the programmer to consult the C# documentation to see what this particular syntax is doing. So instead, C# has you say
Object obj = ...;
if (obj == null)
....
This way, it is obvious what you are trying to do.
This is the same reason why C# requires you to instantiate your local variables as well as declare them before you can use them in code. The value of an uninstantiated variable is ambiguous and depends on the compiler's configuration, so instead of forcing you to do research or perform guesswork, C# instead makes it so you have to code in such a way that your intention is clear.
The fundamental answer to your question is the one given in the accepted answer: because C# was designed to avoid, not perpetuate the design errors of C.
But more specifically: you ask why a type does not implement operator true. The answer to that question is: the purpose of operator true is to implement the short circuiting && and || operators. Since there is no desire to have object implement either & or && or | or ||, there is no reason to implement operator true or operator false.
Boxing.
It would really be horribly confusing for conditionals involving booleans to do the exact opposite when the value is boxed.
What do you want from:
object o = false; // Yes, this is legal, it makes a boxed System.Boolean
if (o) { ... }
For this reason it's fine for bool-like types to be tested in conditions, but not for System.Object which is the base class for all boxed values.

Using an "is" check when with an explicit cast [duplicate]

This question already has answers here:
Casting vs using the 'as' keyword in the CLR
(18 answers)
Closed 9 years ago.
How does the "is" operator work in C#?
I have been told that this :
if (x is string)
{
string y = x as string;
//Do something
}
is not as good as this:
string y = x as string;
if (y != null)
{
//Do something
}
Which is better and why?
FxCop issues Warning CA1800 in the first scenario (and not only when using as, but also when using an unchecked cast) as both is and the actual casts require certain type checking operations to determine whether the cast is successful or whether to throw an InvalidCastException.
You might save a few operations by just using as once and then checking the result for null if you are going to use the cast value anyway, rather than checking explicitly with is and then casting anew.
I think second is better cause in first case it will cast object 2 times, first time with is operator and second time in as operator.
while in second case it cast only one time.
The is operator checks if an object can be cast to a specific type or not
like
if (someObj is StringBuilder)
{
StringBuilder ss = someObj as StringBuilder
....
}
The as operator cast an object to a specific type, and returns null if it fails.
like
StringBuilder b = someObj as StringBuilder;
if (b != null) ...
I would use the first approach when more than one type is expected to be stored in x. (You might be passed a string, or a StringBuilder etc). This would allow for non-exception based handling.
If you are always expecting x to hold a certain type of value, then I would use the second option. The check for null is inexpensive and provides a level of validation.
-- Edit --
Wow. After reading some of the comments below, I started looking for more updated information. There is a LOT more to consider, when using as vs is vs (casting). Here are two interesting reads I found.
Does it make sense to use "as" instead of a cast even if there is no null check? and http://blogs.msdn.com/b/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx?PageIndex=1#comments
Both of which seem to be well summarized by Jon Skeet's blog. http://www.yoda.arachsys.com/csharp/faq/#cast.as

C# - Does OR act like an Else If? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Will all methods in a logical expressions be executed?
Let me explain: let's say we have theese two codes:
foreach(Object o in Objs)
if(o is Class1 || o is Class2)
DoSomething();
__
foreach(Object o in Objs)
if(o is Class1)
DoSomething();
else if(o is Class2)
DoSomething();
Now, of course an OR is better in this case, but my question is different and just out of curiosity: when in the first case o is of type Class1, does the compiler stop and run the code or it checks what comes next anyway?
It would do that in the second case.
|| is short-circuiting, which means: if the first argument returns true, the second argument is not evaluated. In this way, yes it is broadly equivalent to your second example, but more terse.
MSDN Documentation for the || operator in C#
The conditional-OR operator (||) performs a logical-OR of its bool operands. If the first operand evaluates to true, the second operand isn't evaluated. If the first operand evaluates to false, the second operator determines whether the OR expression as a whole evaluates to true or false.
Note: That is also the case for all C-like languages (C, C++, Java, C#) that I know of.
In the operation x || y, y is evaluated only if x is false.
Yes.
The double pipe or "||" will look from the left to the right if some condition is true, whether it will stop looking for other condition and execute the piece of code. The simple pipe or "|" will do the same thing but will check all the conditions (so generally you will prefer using "||").

null == object vs object == null [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is wrong in comparing a null with an object rather than an object with a null
I see some developers using the following null object checking in C#:
if (null == myObject)
{
}
rather than:
if (myObject == null)
{
}
I prefer the second statement, since it reads naturally (for me) from left to right.
Is there any reason for why the first one would be used? Are there any performance benefits, or is it purely taste?
Some people (Mostly C developers) prefer the first way because if you forget one = sign the code wont compile in C.
For example, when i forget one =;
int a = 0;
if(a=1) //Accidental assignment, luckily the C# compiler warns us for this. The C compiler wouldnt.
{
}
if(1=a) // This is not logical, and not valid in either C# or C.
{
}
However as Jamietre pointed out that unlike C its invalid in C# to implicitly cast an int to a boolean. The compiler still produces an error. It will however work when you compare booleans as such: if(a == true). However that in itself is rather odd, as you can (and should in my opinion) omit the == true.
Purely taste. They both will return exactly the same thing.
Pure taste, same as with comas, brackets etc.

Overloading +=, +, ==, and != operators [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why must we define both == and != in C#?
Why is overloading of += possible only by overloading of +, but == and != are separately overloaded?
It seems it should be inverted.
+= overloading is nearly always possible to write more effective because it's unnecessary to allocate memory for new object. But I can't invent an example in which operators == and != should be different in something except inverting the result Equals().
A similar question has been asked before.
The biggest reason is that when you overload the == and != operators, you don't have to return a boolean. If you're not returning a boolean, you can't just invert the complimentary operator. There are other possible reasons they are separately overloaded, you can view the answers to that question for those other reasons.
There is a valid reason you can't overload += and therefore it is done implicitly via the + operator. I has to do with the fact that you can't override the assignment operator in C#, it's part of the language standard. The += is increment and assign, the latter of which you can't overload in C#.

Categories

Resources