I'm brushing up on some C# and had a question that seemed dumb. In C# (and probably most languages), can you put an else statement inside an if-else statement?
e.g.
if (clause) {
execute code
}
else if (clause) {
execute code
else {
execute code
}
}
This should be erroneous.
You probably want something like this instead:
if (clause)
{
// do something
}
else
{
if (anotherClause)
{
// do something
}
else
{
// do something
}
}
I assume you are new to programming, so I can talk a little bit about if else statements.
else does not make any sense when you don't have an if before it.
For example,
This statement makes sense:
IF you are 21 or older, you can drink. ELSE, you cannot drink.
While this does not:
ELSE, you cannot drink
Hopefully my answer helps
it is not possible but you can do something like that instead :
if(condition)
{
//code that get executed after cheking the condition
}
else if(another condition)
{
// code that get executed after checking the second condition
}
else
{
// code get executed if the first and the second condition are not true
}
That code wouldn't work because you need an if for there to be an else. If you want to do an additional check for something within the else if, you need to add an if first, like this:
if (clause)
{
execute code
}
else if (clause)
{
execute code
if (clause)
{
execute code
}
else
{
execute code
}
}
Related
It's such that I have a method that I call 7 times and I would like the code to be made nicer and at the same time easy to read and understand.
How can I hold it somewhere?
Just pt, I'll do like this.
#if(HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) == true)
{
#Html.Raw("col-md-8");
}
else if(HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) == false)
{
#Html.Raw("col-md-12");
}
Basically, I think that you could do this here but it does not work in any way.
Note that I do it for example on the index.cshtml page.
As far I Understand, You call HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId) this function many times from the view; Now you want to store the result in any variable then use the variable all the places.
If it is then try this:
#{
var variableName = HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId);
}
#if(variableName == true)
{
// do your stuff
}
else if(variableName == false)
{
// do your stuff
}
Just store the value in a variable. In this example I use a variable named flag.
#var flag = HelperToTables.ContentText.ContentIdValue.GetInfoContentInfo.GetColBool(Model.HiddenId);
#if (flag)
{
#Html.Raw("col-md-8");
}
else
{
#Html.Raw("col-md-12");
}
I have a validation method which I call in a loop.
I want to call "continue" if the validation fails.
Is there a way to call "continue" from the validation method ?
I just don't want to call "continue" in so many places in the loop...
No, flow control statements only affect the blocks within which they are defined. The only built-in way to alter control flow from further up the stack like that is an exception, which is definitely the wrong mechanism for what you are doing.
If you are bothered by all the continues, I suggest you consider moving towards a more declarative way of thinking. Define the body of your validation loop like so:
bool IsValid(Foo foo) {
if (Condition1(foo)) {
return false;
}
if (Condition2(foo)) {
return false;
}
// ... and so on
}
and then validate like this:
if (!foos.All(IsValid)) {
// One of your foos is invalid
}
the LINQ extension methods All and Any will break execution as soon as they can, meaning that All will stop when it finds the first one that doesn't satisfy the condition and Any will stop when it finds the first one that does.
You have a lot of continues in your cycle and it becomes bothering. You cannot continue from the external method, as it is out of scope. There are several solutions actually though:
You can return a boolean value from your validation methods and then use it as such:
if (!IsValid()) {
continue;
}
It is not helpful though, because you will still have continues.
You can put your validations at the start of the cycle and you can use a flag to determine whether the iteration should step out, initialized by false:
while (myCondition) {
stepOut = false;
//validation region, you set stepOut to false if a validation fails
if (!stepOut) {
//operations
}
}
You can wrap all the validation call into a method, let's call it myValidation and then:
while (myCondition) {
if (myValidation()) {
//operations
}
}
or
while (myCondition) {
if (!IsValid()) {
//continue
}
}
You can throw an Exception, but DON'T do that.
Just return false in your validation method wherever it should return, then check if the validation method returns false, break out of loop in caller function.
Why Not ?
Golden Rule in Programming : "There is always a way".
C++ lets you inline Assembly Language syntax. Similar to it, C# supports it too. Let me consider your example.
void method1(){
foreach(var x in y)
{
Validate(x);
...
//Your other logic
...
EndOfLoop:
;
}
}
..
..
void Validate(T x)
{
#if IL
br EndOfLoop
#endif
}
//End Of Code
This will "jump" to the "EndOfLoop" Label from anywhere within your Code. This could be a bad practice depending on your code though..
Hi I want to stop the execution of if-loop ,I have tried with 'return' statement but its exits from the function ,So how can I exit from the single if Statement.I have tried with following code...
Here I want to stop execution of if(CheckHorizontalSide(SourceMember)) and by stopping this I want to move towards the if(CheckTop(SourceMember))
void A()
{
if (CheckHorizontalSide(SourceMember))
{
if (lblHorizontalMember.Text == DestinationMember)
{
lsRelationPath.Add(lblHorizontalMember.Text);
lblRelationPath.Text = String.Join("-", lsRelationPath);
lblRelationPath.Visible = true;
return;
}
bool WhetherContains = lsRelationPath.Contains(SourceMember);
if (WhetherContains)
{
return;
}
//This below code is not related to the above 'WhetherContains '
lsMemberID1.Clear();
lsRelationPath.Add(lblHorizontalMember.Text);
Find_Route(lblHorizontalMember.Text, DestinationMember);
}
if(CheckTop(SourceMember))
{
//code here....
}
}
You put the rest of the block in a sub-block with { } and put else in front of that.
You can nest as deeply as you want but you might try factoring out blocks to helper functions to reduce the complexity and give statements a name.
if (WhetherContains)
{
// this is actually empty
}
else
{
lsMemberID1.Clear();
lsRelationPath.Add(lblHorizontalMember.Text);
}
Or,
if (!WhetherContains)
{
lsMemberID1.Clear();
lsRelationPath.Add(lblHorizontalMember.Text);
}
I have something like this:
void MethodToBreak()
{
// do something
if(something)
{
MethodThatBreaks();
return;
}
// do something
}
void MethodThatBreaks()
{
// do something
}
So, I was wondering: is it possible to break execution from: MethodThatBreaks()? Then, I would have: if(something) MethodThatBreaks(); and if the condition inside if is true, nothing after that row would be executed.
NOTE: I know it's possible with else in this case, but I don't want that.
It would be a nightmare to maintain if you were to upset execution of one method from another. Trying to figure out why your control flow is all over the place six months down the line, or for a another developer, would be aneurysm-inducing.
There's nothing wrong with what you're already doing there, although personally I'd use an else. Is there a particular reason why you don't want to use else? If it's that the remaining code is too long that's perhaps and indication you should refactor.
Throwing an exception in MethodThatBreaks is one possibility. So in the client of the MethodToBreak you put try catch block.
This can be done by:
declare global variable
a=null;
void MethodToBreak()
{
// do something
if(something)
{
MethodThatBreaks();
if(a==null){
} else{
return;
}
}
// do something
}
void MethodThatBreaks()
{
a="somevalue";
// do something
}
What if I have nested loops, and I want to break out of all of them at once?
while (true) {
// ...
while (shouldCont) {
// ...
while (shouldGo) {
// ...
if (timeToStop) {
break; // Break out of everything?
}
}
}
}
In PHP, break takes an argument for the number of loops to break out of. Can something like this be done in C#?
What about something hideous, like goto?
// In the innermost loop
goto BREAK
// ...
BREAK: break; break; break;
Extract your nested loops into a function and then you can use return to get out of the loop from anywhere, rather than break.
Introduce another control flag and put it in all your nested while condition like below. Also replaces the while(true) condition you have with that
bool keepLooping = true;
while (keepLooping) {
// ...
while (shouldCont && keepLooping) {
// ...
while (shouldGo && keepLooping) {
// ...
if (timeToStop) {
keepLooping = false;
break; // break out of everything?
}
}
}
}
Goto is only hideous when abused. To drop out of the innermost loop of some nesting it's acceptable. BUT... one has to ask why there is so much nesting there in the first place.
Short answer: No.
If you want to break out of an entire method, then use the code below.
If you only want to break out of a series of loops within a method without breaking out of the method, then one of the answers that have already been posted will do the job.
if (TimeToStop)
{
return;
}
You can just use goto to get out of the loops:
[...]
while (true) {
// ...
while (shouldCont) {
// ...
while (shouldGo) {
// ...
if (timeToStop) {
goto GETOUT;
}
}
}
}
GETOUT:
//move on to the next step
[...]