Chaining methods with && - c#

I have a bunch of methods that all return a bool.
If one method returns false then there is no value in calling the following methods, especially as some of them are 'expensive' operations.
Which is the more efficient?
bool result = method1();
if (result) result = method2();
if (result) result = method3();
return result;
or
return method1() && method2() && method3();
As I understand it, the 2nd form should stop evaluating as soon as one of the methods returns false, right?

Yes you are right. Both && and || boolean operators in c# work as short-circuit operator. It stops evaluating expression once its value is determined. It stops unnecessary execution.
Hence return method1() && method2() && method3(); is better option in your case. If you have something in non-evaluated statement, say method3 in your case, it may lead to some side effects.
There is this very good language independent article about short-circuit operators on Wikipedia.
UPDATE:
In C# if you want to use logical operator without short-circuit, use & and | operator instead.

Yes, the two methods are equivalent. Using && is a shortcut to achieve the same result as using a backing variable.

The second will stop the expression evaluation after the first expression is evaluated to false.
although both examples are semantically equivalent the second one is more readable in my opionion.

Related

How do C# lambdas work without a “return”?

I have occasionally come across statements like this
school.Where(s => s.name == "foo")
Now I understand this is a lambda and I think I am comfortable with lambdas. I just started C# so I do have this question. In the statement
s => s.name == "foo"
how is the evaluation return being done to determine true or false. I do not see a return statement ? All i see is a comparison operation in the lambda body and nothing being returned. Can anyone please explain this to me.
In this form the return is implicit. The lambda returns whatever the expression returns. You could also write it like this:
s => { return s.name == "foo"; }
The reason why the return isn’t needed in the short form is because that’s how the language was designed. It makes things short and nice to use instead of forcing the developer to write unnecessary code.
The return statement is implied. If you were to add brackets around s.name == "foo" then you'd have to have a return. The compiler essentially creates a function to be called there for you. This is just syntax sugar. It's equivalent to creating a function yourself and passing that into the Where
Lambda can be defined in two ways:
with curly braces: then you will have to write body of a method, just like in a regular method, i.e. with returns, etc. Example
var lambda = (string param) => { return param.Length; };
without curly braces: then the method has to contain one line, which also be the result of a method. Example:
var lambda = (string param) => param.Length;
This is by design, to make one-line methods look nice and clean (especially in LINQ extensoin methods) :)
The returned value is always boolean and you can get it like below:
s=> {retutn s.name=="foo";}

Is It Possible to have the Compiler Automatically Optimize my "OR" Statements?

Is there a way to make the C# compiler optimize my OR clauses in an if statement?
For example:
if(Function_that_returns_boolean() || boolean_value)
{
// Do something here...
}
Could have hugely different execution times than
if(boolean_value || Function_that_returns_boolean())
{
// Do something here...
}
depending on how much work Function_that_returns_boolean() actually does internally.
It's unlikely (and perhaps impossible) that the compiler could know exactly how efficient Function_that_returns_boolean() is, and all of my (brief) testing indicates OR statements are always processed left to right, even under using the most aggressive compiler optimizations.
Is this already handled by the compiler (i.e. am I mistaken)? If not, are there any hints I can give to it?
Maybe something like an Attribute that lets the compiler know that it's free to rearrange my code (and if not present, to leave it be)?
[OrStatementUsage(Speed.Fast)] // Always push statement left when possible
public bool Fast_function_that_returns_boolean()
{
return a + b == c; // fast
}
[OrStatementUsage(Speed.Slow)] // Always push statement right when possible
public bool Slow_function_that_returns_boolean()
{
Thread.Sleep(1000);
return a + b == c; // slow
}
(Note: all methods in the statement would have to be tagged and side-effect free to be candidates for rearrangement)
http://msdn.microsoft.com/en-us/library/6373h346.aspx
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.
The first operand will always be evaluated. This is a very important guarantee:
if (obj == null || obj.foo == "bar")
If the compiler could reorder the conditions here, it would change the functionality of the program.
The compiler can't know whether a given reordering would affect the result -- both because it can't in general know what the result will be and because it doesn't know what parts of the result are important. Maybe you want a long delay, or the first calculation does something important for the correctness of the program.
No, the first argument is evaluated, and if it is true, the second argument is not evaluated at all. It is called "short-circuit" evaluation.
See http://msdn.microsoft.com/en-us/library/6373h346.aspx.
There is no way to instruct the compiler to evaluate the second argument of || first.
No, boolean logic operators are always short-circuit evaluated. In case of an or, the second part might not even be evaluated if it already evaluated to true. For instance:
if(ReturnTrue() || SlowOperation()) { /* ... */ }
Assuming that ReturnTrue() returns true, SlowOperation() is never called. The compiler cannot make optimization based on some arbitrary assumptions

boolean operation on methods [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Does the compiler continue evaluating an expression where all must be true if the first is false?
Difference between eager operation and short-circuit operation? (| versu || and & versu &&)
So here's my question. If I have this
if (Foo() && Bar())
DoStuff();
if Foo() returns false, will it still run through Bar()? or do I need to have
if (Foo())
if (Bar())
DoStuff();
to ensure that it only runs through the minimum amount needed before "failing out"?
if (Foo() && Bar())
In this case (logical AND) it will firstly check Foo() return value and will do Bar() only if Foo() returns true. Simply if any of conditions is false then it will not check others, it will check conditions from left to right.
No, Bar() won't be evaluated if Foo() returns false. It's a feature of the C# && operator (not limited to if statements):
The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.
What you are looking for is called "Short-circuiting," and yes, .Net supports it.

Benefits of using the conditional ?: (ternary) operator

What are the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being:
Conditional ?: Operator
Shorter and more concise when dealing with direct value comparisons and assignments
Doesn't seem to be as flexible as the if/else construct
Standard If/Else
Can be applied to more situations (such as function calls)
Often are unnecessarily long
Readability seems to vary for each depending on the statement. For a little while after first being exposed to the ?: operator, it took me some time to digest exactly how it worked. Would you recommend using it wherever possible, or sticking to if/else given that I work with many non-programmers?
I would basically recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the if/else equivalent without sacrificing readability.
Good example:
int result = Check() ? 1 : 0;
Bad example:
int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;
This is pretty much covered by the other answers, but "it's an expression" doesn't really explain why that is so useful...
In languages like C++ and C#, you can define local readonly fields (within a method body) using them. This is not possible with a conventional if/then statement because the value of a readonly field has to be assigned within that single statement:
readonly int speed = (shiftKeyDown) ? 10 : 1;
is not the same as:
readonly int speed;
if (shifKeyDown)
speed = 10; // error - can't assign to a readonly
else
speed = 1; // error
In a similar way you can embed a tertiary expression in other code. As well as making the source code more compact (and in some cases more readable as a result) it can also make the generated machine code more compact and efficient:
MoveCar((shiftKeyDown) ? 10 : 1);
...may generate less code than having to call the same method twice:
if (shiftKeyDown)
MoveCar(10);
else
MoveCar(1);
Of course, it's also a more convenient and concise form (less typing, less repetition, and can reduce the chance of errors if you have to duplicate chunks of code in an if/else). In clean "common pattern" cases like this:
object thing = (reference == null) ? null : reference.Thing;
... it is simply faster to read/parse/understand (once you're used to it) than the long-winded if/else equivalent, so it can help you to 'grok' code faster.
Of course, just because it is useful does not mean it is the best thing to use in every case. I'd advise only using it for short bits of code where the meaning is clear (or made more clear) by using ?: - if you use it in more complex code, or nest ternary operators within each other it can make code horribly difficult to read.
I usually choose a ternary operator when I'd have a lot of duplicate code otherwise.
if (a > 0)
answer = compute(a, b, c, d, e);
else
answer = compute(-a, b, c, d, e);
With a ternary operator, this could be accomplished with the following.
answer = compute(a > 0 ? a : -a, b, c, d, e);
I find it particularly helpful when doing web development if I want to set a variable to a value sent in the request if it is defined or to some default value if it is not.
A really cool usage is:
x = foo ? 1 :
bar ? 2 :
baz ? 3 :
4;
Sometimes it can make the assignment of a bool value easier to read at first glance:
// With
button.IsEnabled = someControl.HasError ? false : true;
// Without
button.IsEnabled = !someControl.HasError;
I'd recommend limiting the use of the ternary(?:) operator to simple single line assignment if/else logic. Something resembling this pattern:
if(<boolCondition>) {
<variable> = <value>;
}
else {
<variable> = <anotherValue>;
}
Could be easily converted to:
<variable> = <boolCondition> ? <value> : <anotherValue>;
I would avoid using the ternary operator in situations that require if/else if/else, nested if/else, or if/else branch logic that results in the evaluation of multiple lines. Applying the ternary operator in these situations would likely result in unreadable, confusing, and unmanageable code. Hope this helps.
The conditional operator is great for short conditions, like this:
varA = boolB ? valC : valD;
I use it occasionally because it takes less time to write something that way... unfortunately, this branching can sometimes be missed by another developer browsing over your code. Plus, code isn't usually that short, so I usually help readability by putting the ? and : on separate lines, like this:
doSomeStuffToSomething(shouldSomethingBeDone()
? getTheThingThatNeedsStuffDone()
: getTheOtherThingThatNeedsStuffDone());
However, the big advantage to using if/else blocks (and why I prefer them) is that it's easier to come in later and add some additional logic to the branch,
if (shouldSomethingBeDone()) {
doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
doSomeAdditionalStuff();
} else {
doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
}
or add another condition:
if (shouldSomethingBeDone()) {
doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
doSomeAdditionalStuff();
} else if (shouldThisOtherThingBeDone()){
doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
}
So, in the end, it's about convenience for you now (shorter to use :?) vs. convenience for you (and others) later. It's a judgment call... but like all other code-formatting issues, the only real rule is to be consistent, and be visually courteous to those who have to maintain (or grade!) your code.
(all code eye-compiled)
One thing to recognize when using the ternary operator that it is an expression not a statement.
In functional languages like scheme the distinction doesn't exists:
(if (> a b) a b)
Conditional ?: Operator
"Doesn't seem to be as flexible as the if/else construct"
In functional languages it is.
When programming in imperative languages I apply the ternary operator in situations where I typically would use expressions (assignment, conditional statements, etc).
While the above answers are valid, and I agree with readability being important, there are 2 further points to consider:
In C#6, you can have expression-bodied methods.
This makes it particularly concise to use the ternary:
string GetDrink(DayOfWeek day)
=> day == DayOfWeek.Friday
? "Beer" : "Tea";
Behaviour differs when it comes to implicit type conversion.
If you have types T1 and T2 that can both be implicitly converted to T, then the below does not work:
T GetT() => true ? new T1() : new T2();
(because the compiler tries to determine the type of the ternary expression, and there is no conversion between T1 and T2.)
On the other hand, the if/else version below does work:
T GetT()
{
if (true) return new T1();
return new T2();
}
because T1 is converted to T and so is T2
If I'm setting a value and I know it will always be one line of code to do so, I typically use the ternary (conditional) operator. If there's a chance my code and logic will change in the future, I use an if/else as it's more clear to other programmers.
Of further interest to you may be the ?? operator.
The advantage of the conditional operator is that it is an operator. In other words, it returns a value. Since if is a statement, it cannot return a value.
There is some performance benefit of using the the ? operator in eg. MS Visual C++, but this is a really a compiler specific thing. The compiler can actually optimize out the conditional branch in some cases.
The scenario I most find myself using it is for defaulting values and especially in returns
return someIndex < maxIndex ? someIndex : maxIndex;
Those are really the only places I find it nice, but for them I do.
Though if you're looking for a boolean this might sometimes look like an appropriate thing to do:
bool hey = whatever < whatever_else ? true : false;
Because it's so easy to read and understand, but that idea should always be tossed for the more obvious:
bool hey = (whatever < whatever_else);
If you need multiple branches on the same condition, use an if:
if (A == 6)
f(1, 2, 3);
else
f(4, 5, 6);
If you need multiple branches with different conditions, then if statement count would snowball, you'll want to use the ternary:
f( (A == 6)? 1: 4, (B == 6)? 2: 5, (C == 6)? 3: 6 );
Also, you can use the ternary operator in initialization.
const int i = (A == 6)? 1 : 4;
Doing that with if is very messy:
int i_temp;
if (A == 6)
i_temp = 1;
else
i_temp = 4;
const int i = i_temp;
You can't put the initialization inside the if/else, because it changes the scope. But references and const variables can only be bound at initialization.
The ternary operator can be included within an rvalue, whereas an if-then-else cannot; on the other hand, an if-then-else can execute loops and other statements, whereas the ternary operator can only execute (possibly void) rvalues.
On a related note, the && and || operators allow some execution patterns which are harder to implement with if-then-else. For example, if one has several functions to call and wishes to execute a piece of code if any of them fail, it can be done nicely using the && operator. Doing it without that operator will either require redundant code, a goto, or an extra flag variable.
With C# 7, you can use the new ref locals feature to simplify the conditional assignment of ref-compatible variables. So now, not only can you do:
int i = 0;
T b = default(T), c = default(T);
// initialization of C#7 'ref-local' variable using a conditional r-value⁽¹⁾
ref T a = ref (i == 0 ? ref b : ref c);
...but also the extremely wonderful:
// assignment of l-value⁽²⁾ conditioned by C#7 'ref-locals'
(i == 0 ? ref b : ref c) = a;
That line of code assigns the value of a to either b or c, depending on the value of i.
Notes
1. r-value is the right-hand side of an assignment, the value that gets assigned.
2. l-value is the left-hand side of an assignment, the variable that receives the assigned value.

c#: can you use a boolean predicate as the parameter to an if statement?

In C#, can you use a boolean predicate on its own as the parameter for an if statement?
eg:
string str = "HELLO";
if (str.Equals("HELLO"))
{
Console.WriteLine("HELLO");
}
Will this code output "HELLO", or does it need to be:
string str = "HELLO";
if (str.Equals("HELLO") == true)
{
Console.WriteLine("HELLO");
}
If there is anything else wrong with the above code segments, please point it out.
EDIT: double equals as per answers
Well, the latter snippet won't even compile because it's trying to assign true to str.Equals("Hello") (you've got a single = instead of ==) but either:
if (str.Equals("HELLO"))
or
if (str.Equals("HELLO") == true)
will work. The latter is pretty strongly discouraged though - it's pretty ugly.
Bear in mind that string overloads ==, so you can actually write:
if (str == "HELLO")
which is somewhat simpler.
The second version won't even compile, since you need ==, not =.
Seeing code like if (foo == true) makes bile rise up into my mouth.
Yes you can.
(Your second example needs 2 = (i.e. ==) to be correct).
can you use a boolean predicate on its own as the parameter for an if statement
Strictly speaking, the answer to this is 'no', because a predicate is a function (in the mathematical sense). What you can use for the conditional expression in an if is any boolean expression, including (as here) the result of the invocation of a predicate on a value.
To expand, the 'predicate' here is 'equals HELLO'. It is a function (in the mathematical sense) that operates on values of type string, and returns boolean values. Once you have obtained a boolean value (by applying this function to a particular string, str), you do not need to explicitly compare it to true: you can just use it.
As you will see from others' answers, code in which expressions of boolean type are explicitly compared to boolean literals will often cause code-style pain in the reader :) (My 'favourite' peeve is <boolean expression> ? true : false).
The code you have is correct, the if statement checks to see if the statement within the brackets evaluates to true.
Remember that comparisons in c# use == not = , so it should be if (x == true)
This can be used in other situations like:
bool isACat = true;
if (isACat)
{
}
It is good practice to put is or a similar identifier (Is/Has/Should/Will/Do/Must...) before boolean variable names, as it makes it easy to read when you are not using == true.
There's nothing wrong.
Just two different ways of picking up the same spoon to feed yourself ;)

Categories

Resources