How can I go about doing this so if the "if" statement is true, to skip the code below the foreach loop and to go on with the rest of the program
void()
{
foreach()
{
if()
{
}
}
//code I want to skip if "if" statement is true
}
There's no way to directly do what you want (without "goto" labels -- perish the thought!), but you can use the "break" keyword, and set a variable you can refer to later.
void()
{
var testWasTrue = false;
foreach()
{
if()
{
testWasTrue = true;
break; // break out of the "foreach"
}
}
if( !testWasTrue ) {
//code I want to skip if "if" statement is true
}
}
I know this was already answered, but I figured I'd throw in my 2 cents since nobody considered abstracting the check to a separate method:
void()
{
if (ShouldDoStuff(myCollection))
DoStuff(myCollection);
else
DoOtherStuff(myCollection);
}
private bool ShouldDoStuff(collection)
{
foreach()
{
if ()
return true;
}
return false;
}
This provides a much cleaner code at the higher level for dealing with your algorithms and removes all the clutter discussed about. It cleanly separates the tasks in void() of checking and performing the actions and readers instantly know exactly what the program flow is without having to discern what they're doing with a boolean or break logic lurking about. No single method has more than 1 responsibility or task.
Yeah, it's possible the poster wants to do other work in their foreach, but that's an entirely different discussion and not what was described in their question. If you simply want to check if the given collection (or object) satisfies a certain condition, that check can be moved to a separate method. Even leaves the door open for automated unit tests for all three components.
Even if DoStuff and DoOtherStuff are not abstracted to their own methods, it provides nicer readability and logical flow.
void()
{
bool process = true;
foreach()
{
if()
{
process = false;
break;
}
}
if (process)
{
//code I want to skip if "if" statement is true
}
}
As was mentioned in my comment you may do this through extra bool variable.
void()
{
bool positiveResult; // by default it gets false value
foreach()
{
if()
{
positiveResult = true;
// you may use "break" to skip the loop
break;
}
}
if( !positiveResult )
{
//code I want to skip if "if" statement is true
}
}
The 'break' keyword will break out of the loop.
foreach (someClass a in someArray)
{
if(a.someProperty) // bool property
{
//Stuff to do if that condition is true
doSomethingElse();
//Calling the break keyword will stop the loop and jump immediately outside of it
break;
}
//Other code to run for each iteration of the loop
}
//Here is where execution will pick up either after break is called or after the loop finishes
Only way I know how is a bool flag.
void()
{
bool x = false;
foreach()
{
if()
{
x = true;
break;
}
}
if(!x)
{
//Code to skip if "if" statement is true.
}
}
Not super elegant, but easy.
Edit: beat by 12 secs :)
void()
{
bool skip = false;
foreach()
{
if()
{
skip = true;
}
}
if(!skip)
{
//code I want to skip if "if" statement is true
}
}
If the collection you are iterating through contains The IEnumerable Interface, You could use Any() with a Lambda!
int[] myArray = { 1, 2, 3 };
if( myArray.Any((a) => a == 1) )
{
return;
}
It is read: if my array contains any value a where a is equal to 1, then return out of this function.
Plus if you want to make it harder to read, you can omit the curly braces/brackets.
if( myArray.Any((a) => a == 1) )
return;
Related
What is the most professional code-style in the below two functions ?
And what if the function become more complex & larger such as to have 20 checks ?
Note: i need to do some stuff after each check, so i can't concatenate all in one if-statement like:
if (vehicle.isBus) && (vehicle.numberOfWheels == 6) && (vehicle.motorVersion == 2019)
//first alternative
public bool validate(Vehicle vehicle)
{
if(vehicle.isBus)
{
//do some stuff here related to vehicle.isBus
if (vehicle.numberOfWheels == 6)
{
//do some stuff here related to vehicle.numberOfWheels
if (vehicle.motorVersion == 2019)
{
//do some stuff here related to vehicle.motorVersion
return true;
}
}
}
return false;
}
//second alternative
public bool validate(Vehicle vehicle)
{
if (!vehicle.isBus)
{
return false;
}
//do some stuff here related to vehicle.isBus
if (vehicle.numberOfWheels != 6)
{
return false;
}
//do some stuff here related to vehicle.numberOfWheels
if (vehicle.motorVersion != 2019)
{
return false;
}
//do some stuff here related to vehicle.motorVersion
return true;
}
One golden rule I follow is to Avoid Nesting as much as I can.
Use the one that makes the code more readable and understandable. For just two conditions, the first way is more logical and readable. It might not be the case anymore with 5 or 6 conditions linked with &&, || and !.
So when the number of checks are 5+ then you should prefer second alternative.
Note : Multiple ifs without each calling return implies that 2 or more ifs could be true.
The second example should require less cognitive overhead while reading the code.
In the first example, you need to keep a mental "stack" of the program state. In the second example, you just need to keep a list of things that you already know to be true.
The second example is also less likely to be confounded by a misplaced brace; in fact it doesn't require any braces at all in this example.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why is it good practice to return at the end of a method
I would like to know if could be considered good practice use several RETURN statements in a method and why.
If not, I would like to know how you would rewrite the code in a different way.
public string GetNominativeById(int? candidateId)
{
if (candidateId.HasValue)
return repepositoryCandidate.GetById(candidateId.Value).Nominative;
else
return string.Empty;
}
}
With one RETURN
public string GetNominativeById(int? candidateId)
{
string result;
if (candidateId.HasValue)
result = repepositoryCandidate.GetById(candidateId.Value).Nominative;
else
result = string.Empty;
return result;
}
}
You don't actually need else
string GetNominativeById(int? candidateId)
{
if (!candidateId.HasValue)
return string.Empty;
return repepositoryCandidate.GetById(candidateId.Value).Nominative;
}
Consider this anti arrow pattern:
if (condition1)
{
if (condition2)
{
if (condition3)
{
// code lines
}
}
}
the way to return immediately will make your code more readable:
if (!condition1) return;
if (!condition2) return;
if (!condition3) return;
// code lines
No, it's considered bad practice not so good practice to have multiple exit points in a method. It's easier to follow the code if there is a single point of exit.
However, when the method is as small as in the example, it's not hard to follow the code anyway, so having multiple exit points is not really a problem. If it makes the code simpler, you can very well use multiple return statements.
Although you should strive to have only one return statement for readability purposes the are several patterns that involve multiple return statements. One example is Guard Clause.
Example of guard clause:
public Foo merge (Foo a, Foo b) {
if (a == null) return b;
if (b == null) return a;
// complicated merge code goes here.
}
Some style guides would have us write this with a single return as follows
public Foo merge (Foo a, Foo b) {
Foo result;
if (a != null) {
if (b != null) {
// complicated merge code goes here.
} else {
result = a;
}
} else {
result = b;
}
return result;
}
Another case is a switch statement when you might want to return from each case:
switch(foo)
{
case "A":
return "Foo";
case "B":
return "Bar";
default:
throw new NotSupportedException();
}
I would rewrite your code as:
public string GetNominativeById(int? candidateId)
{
return candidateId.HasValue
? repepositoryCandidate.GetById(candidateId.Value).Nominative;
: string.Empty;
}
At the end of the day, remember that you (and other developers) will be reading your code many times, so make sure that it's readable and obvious.
Take a look at the following Article on Wikipedia. What you're asking is whether you should follow the SESE (single entry, single exit) principle from structured programming.
One of the rules of Structured programming states that each method should have a single entry and exit point. Having a single exit point (return statement in this case) means any clean up, such as calling Close or Dispose, only needs to happen once. The impact of having multiple exit points is minor on small methods but increases as method complexity increases, where it may be easy to miss a case, or as code as refactored or modified.
there is nothing wrong with having more return statement, sometimes it actually help you minify your code and save some unnecessary variable assign like what Cuong Le did pointed out. :D
make it a habit to add return at the end of the method, so you will have to close any active objects (if you have)
public string GetNominativeById(int? candidateId)
{
string _returnValue = string.Empty;
if (candidateId.HasValue)
_returnValue repepositoryCandidate.GetById(candidateId.Value).Nominative;
else
_returnValue = string.Empty;
return _returnValue;
}
side-note: Ternary Operator is not really an answer on this (I think) because there are some case that you multiple code blocks in your IF statement.
All this depends on
coding standard you use with other developers
and actual code readability (so personal perception of the code)
In general, when if/else becomes too much, I use return instead.
So instead of using:
if(...)
{
if(...)
{
if(...)
{
}
}
else if(...)
{
}
..
else
{
}
}
use a return:
if(!...)
return;
if(!...)
return;
you actually can not use more than one return statement in a single method, what you did in your code, you used a if else statement, so only one will be executed anyway. Your code seems good to me.
Yes if it is necessary then why not use several return statements. There will be no issue with the performance.
To rewrite this code:
public string GetNominativeById(int? candidateId)
{
if (candidateId.HasValue)
return repepositoryCandidate.GetById(candidateId.Value).Nominative;
return string.empty;
}
OR use "ternary operator".
public string GetNominativeById(int? candidateId)
{
return candidateId.HasValue ? repepositoryCandidate.GetById(candidateId.Value).Nominative : string.Empty;
}
Why not? But you don't need else.
public string GetNominativeById(int? candidateId)
{
if (candidateId.HasValue)
return repepositoryCandidate.GetById(candidateId.Value).Nominative;
return string.Empty;
}
I know this is a very newbie C# question but I am implementing a small program which does the following:
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
bool isRun = false;
int number = 0;
while (isRun = (true) && number < 3)
{
++number;
Console.WriteLine("Number = {0}", number.ToString());
Console.WriteLine();
}
Console.WriteLine(isRun.ToString());
Console.ReadLine();
}
}
}
At the end of the while loop, I would have expected the bool value to be true, but is is printed to be false. Why is that? Is this different from C++ where I would have done something like and the same thing in C# is giving me false
while(number<3)
{
is = true;
}
if(is){
cout<<true;
}
The reason you're seeing this behavior is due to the operator precedence involved. Here the && binds more strongly than = so the code in the loop is actually bound as the following
while (isRun = (true && number < 3)) {
...
}
Once number > 3 the && expression is false and is assigned into the isRun value and simultaneously terminates the loop. Hence once the loop exits you will see isRun as false
To get the behavior you are looking for you will need to manually correct the precedence with parens.
while ((isRun = (true)) && number < 3) {
...
}
Note: In general, as #Servey pointed out, the assignment of locals to expressions inside the loop predicate is considered bad practice. Many C# users would actually be surprised that code compiles at all because they've been conditioned to only use == in loops.
It's more idiomatic to simply set isRun to true on the first line of the loop for this pattern.
while (number < 3) {
isRun = true;
...
}
The problem is that you have set you boolean variable to false and without assigning it back to true, in while loop you are matching it against the value true, thus it fails in every case.
This is my recursive function :
public bool controllaSelezioneSottopagina(KPage k_oPaginaAttuale, KPage k_oPaginaSuperiore)
{
foreach (KPage k_oSottoPagina in k_oPaginaSuperiore.SottoPagine)
{
if (k_oSottoPagina.ID == k_oPaginaAttuale.ID)
{
return true;
}
else
{
if (k_oSottoPagina.SottoPagine.Count != 0)
{
controllaSelezioneSottopagina(k_oPaginaAttuale, k_oSottoPagina);
}
}
}
return false;
}
I aspect, from where I call it, to get ALWAYS false (the return false at the end of the function, will be the last result that will be returned, EVER).
In fact, sometimes it returns true.
How it is possible? Tried debugging... but I can't find out the mistake...
You call the function once, then it loops, and either returns true or calls itself recussively. It will only return false if it loops through all elements and the condition (k_oSottoPagina.ID == k_oPaginaAttuale.ID) is never met.
Now assume that this condition is actually met in the first level (there was no recursion made yet or all recursive call return).
You call the function once, it loops and for example on the first test this condition is true. Then you will see a return value 'true'
I think this could happen only in first iteration. I mean that only first comparison may result in returning true. Recursive call would never happen then.
Are you saying this code block will never be true in the first call to the function (the first time through the loop)?
k_oSottoPagina.ID == k_oPaginaAttuale.ID
Since you don't return the result of the recursive call, your function either blows the stack, returns true through the first loop at some point, or finishes the loop and returns false.
another alternative to not printing incorrect false in the cases where it does go in the loop is
public bool controllaSelezioneSottopagina(KPage k_oPaginaAttuale, KPage k_oPaginaSuperiore)
{
foreach (KPage k_oSottoPagina in k_oPaginaSuperiore.SottoPagine)
{
if (k_oSottoPagina.ID == k_oPaginaAttuale.ID)
{
return true;
}
else
{
if (k_oSottoPagina.SottoPagine.Count != 0)
{
if(controllaSelezioneSottopagina(k_oPaginaAttuale, k_oSottoPagina))
{
return true;
}
}
}
}
return false;
}
Good evening,
I was wondering if I could do something like:
while(true)
{
MyEnum currentValue = GetMyEnumValueFromDB();
if(currentValue == MyEnum.BreakIfYouGetThis)
break;
else if(currentValue == MyEnum.AlsoBreakIfYouGetThis)
break;
else
//Do some computing
}
But instead of having a while(true) loop, I'd want to encapsulate the conditional logic in a Func and execute it like this:
while(new Func<bool>(/* what goes here? */))
{
//Do some computing
}
In my case at least, it would look much cleaner, but i'm not sure how to do it (kinda new at Func/Action..).
EDIT hope this clarifies:
It could also be done like this:
while(GetMyEnumValueFromDB() != MyEnum.BreakIfYouGetThis &&
GetMyEnumValueFromDB() != MyEnum.AlsoBreakIfYouGetThis)
{
//Do some computing
}
But that's 2 call to the database...
Thanks =)
Well you could have:
Func<bool> condition = ...;
while (condition())
{
}
Is that what you're thinking of? It's not really clear...
EDIT: In the example you've given, I'd use something like:
private static readonly MyEnum[] BreakEnumValues = {
MyEnum.BreakIfYouGetThis,
MyEnum.AlsoBreakIfYouGetThis
};
...
while (!BreakEnumValues.Contains(GetMyEnumValueFromDB()))
{
...
}
Or:
private static bool ShouldBreak(MyEnum enumFromDatabase)
{
return enumFromDatabase == MyEnum.BreakIfYouGetThis ||
enumFromDatabase == MyEnum.AlsoBreakIfYouGetThis;
}
...
while (!ShouldBreak(GetMyEnumValueFromDB))
{
...
}
EDIT: To counter KeithS's answer, this is entirely valid:
while (new Func<bool>(() => {
Console.WriteLine("Evaluating...");
return true;
})()) {
Console.WriteLine("In loop");
count++;
if (count == 5)
{
break;
}
}
It's horrible, but it's valid. (It can be made slightly less horrid by explicitly calling Invoke, but it's still not nice.)
You could do that, but if you don't have a compelling reason to do so (like you're passing the condition function in as a parameter), I'd just wrap your logic in a function and call it directly:
while(KeepGoing())
{
//Do stuff
}
bool KeepGoing()
{
// Check conditions for continuing
var value = GetMyEnumValueFromDB();
return value != MyEnum.BreakIfYouGetThis && value != MyEnum.AlsoBreakIfYouGetThis;
}
First off, a database call in a while loop is a bad idea. Query what you'll need beforehand and loop accordingly.
It appears that polymorphism can be your friend here. If you need to keep the same flow, you can do something like this:
interface IWhileLoopContinuable
{
bool KeepGoing {get;}
void DoWork();
}
Then you can use TakeWhile on this enumerable:
foreach(var item in queriedAsIWhileLoopContinuable.TakeWhile(c => c.KeepGoing))
{
item.DoWork();
}
All that being said, you could just query for what you want and work on that.
Well, first off you cannot "new" a Func, just like you can't new up any delegate type. You must instead assign an existing named method or function literal (aka anonymous delegate, lambda, etc) to initialize a Func variable.
//these won't compile; Func has no constructor
Func<bool> condition = new Func<bool>();
//As Jon Skeet notes, these will compile because of language-provided syntax,
//even though Funcs have no constructor with a delegate parameter.
Func<bool> condition = new Func<bool>(SomeNamedMethodReturnsBool);
Func<bool> condition = new Func<bool>(()=>true);
//and these will compile because you're directly assigning the delegate
Func<bool> condition = SomeNamedMethodReturnsBool;
Func<bool> condition = ()=>true;
You actually cannot do what you want in C#; an anonymous delegate must be assigned to a variable or parameter in order to be used. It cannot be used in-place as a "function literal" in the abstract sense.
Even if you could, the utility of such a statement escapes me. The delegate would not be re-instantiated every time (the compiler turns anonymous delegates into named private functions of the containing class, with mashup names), but you're adding a layer onto the call stack just to evaluate a constant expression that could be placed directly into the parenthesis of the while() statement. The main utility of an anonymous delegate would be that you could swap out lambdas at runtime, and in order to do that you MUST have a variable.