How do I do this? I have an if-else statement like this (not exact code but a symbolic idea):
if(formNull)
{
MessageBox.Show("empty")
}
else if(FormNotNull)
{
// I have validation if/elses here for input fields like
if(regex textbx1)
{
error
}
else
{
normal
}
if(regex textbx2)
{
error
}
else
{
normal
}
//Some more like this
} <<<<<<<<<<<< It stops here and never goes in the next 'else' statement even if the form is OK.
else
{
DBConn.myMethod(a, b, c, etc.)
if true
{
success!;
}
else
{
failed!;
}
}
I tried some nesting combinations, but nothing worked.
Seems like there's nothing left, as you already handled all cases in the if and else if.
if(formNull)
{
// goes here when `formNull` is true
}
else if(FormNotNull)
{
// goes here when `FormNotNull` is true and `formNull` is false
}
else
{
// goes here in any other case (but I guess there is no other case left)
}
That just means your two conditions (in the if and else if statements) are returning true. If either ever returns true, you will never go into your else block (both MUST be false).
Thank you all for suggestions. I simply used the separate textChanged events with Regex for errors and used simple if-statement like this
if (FormNull)
{
Message.Show("error");
}
else
{
DBConn.myMthod(a,b,c)
if(true)
{
sucess;
}
else
{
failed;
}
}
Just wanted to know the other option for what I was trying to do.
Related
Sample code below is just a short one, my real code for one if statement is more than 1000 lines of code and those need to be called multiple times. So, to save lines I plan on putting it into a method and just calling that method, which is only around 1 line?
I was wondering if there is a possible way of putting multiple if else statements into MULTIPLE methods, and then calling those methods in the main method. If Method SuperSignalQ1 is true, then it will check method SuperSignalQ2, and so on.
I need this because without the method, my current code is more than 900k, which crashes my PC. This is the only way I could think of shortening my code, by putting it into a method and calling it in the main method as needed, rather than typing those 100s of lines everytime I need those.
So basically my question is:
How to call a method in the main method
How to check if that method is true so that it can then proceed to the next method. I receive error when doing the code in the MainCalculation
Cannot convert method group 'SuperSignalQ1' to non-delegate type 'bool'. Did you intend to invoke the method?
public void SuperSignalQ1()
{
if(RSI > RSI2)
{
if(CCI > CCI2) //There are actually more than 20 if else here which is around 1000 lines
{
return;
}
}
}
public void SuperSignalQ2()
{
if(RSI2 > RSI3)
{
if(CCI2 > CCI3) //There are actually more than 20 if else here which is around 1000 lines
{
return;
}
}
}
public void SuperSignalQ3()
{
if(RSI3 > RSI4)
{
if(CCI3 > CCI4) //There are actually more than 20 if else here which is around 1000 lines
{
return;
}
}
}
public void MainCalculation()
{
if (SuperSignalQ1 = True)
{
if(SuperSignalQ2 = True)
{
if SuperSignalQ3 = True)
{
SetColor(Color.White);
}
}
}
}
So basically, put multiple nested if statement into multiple methods, and then do an boolean check of those methods in the main method
You have
public void SuperSignalQ1()
and later on you have
if (SuperSignalQ1 = True)
This if statement is broken.
In c#, you test with the double equals:
if (someVariable == true)
What you've got is an assignment statement, because there's one equals sign.
You're also missing some brackets, so C# thinks you are referring to it as a variable instead of a method.
So it thinks you are trying to assign a value of True to the method pointer. Which it quite rightly complains about.
It looks like you actually want those methods to return a boolean value, and you could do something like this:
public bool SuperSignalQ1()
{
if(RSI > RSI2)
{
if(CCI > CCI2) //There are actually more than 20 if else here which is around 1000 lines
{
return true;
}
}
return false; // if none of the conditions are valid
}
public bool SuperSignalQ2()
{
if(RSI2 > RSI3)
{
if(CCI2 > CCI3) //There are actually more than 20 if else here which is around 1000 lines
{
return true;
}
}
return false; // if none of the conditions are valid
}
public bool SuperSignalQ3()
{
if(RSI3 > RSI4)
{
if(CCI3 > CCI4) //There are actually more than 20 if else here which is around 1000 lines
{
return true;
}
}
}
public void MainCalculation()
{
if (SuperSignalQ1() == true)
{
if(SuperSignalQ2() == true)
{
if (SuperSignalQ3() == true)
{
SetColor(Color.White);
}
}
}
}
BUT
For boolean, you don't usually use the == format, you'd just go if (SuperSignalQ1())
As #aether643 suggested, you might want to refactor your code so you don't have such a long chunk of code without mental breaks
In C#, you can actually do assignments in if tests. Don't do that.
The code below is a snippet from a working code that is for a castle maze game in c#.
The if else structure only prints correctly the dun.roomend == true). The tow.roomEnd now displays when the tre.isExit should be displayed. The tre.isExit doesn't display at all.
I have declared the current variables as:
public bool isExit;
public bool deadEnd;
public bool roomEnd;
tre.isExit = true;
dun.deadEnd = true;
tow.roomEnd = true;
if (dun.roomEnd == true)
{
Console.WriteLine("You've fallen into the Dungeons of the Dead. Try again");
return;
}
if (tow.roomEnd == true)
{
Console.WriteLine("You been caught by the Kings guard and have been placed in the tower for life.Try again");
return;
}
else if (tre.isExit == true)
{
Console.WriteLine("You have found the treaure... now run!!");
return;
}
else
{
Console.WriteLine("Too scared.....");
}
That's because you immediately return when one of your conditions is true.
// Don't explicitly compare to true - just write if (dun.roomEnd)
if (dun.roomEnd == true)
{
Console.WriteLine("You've fallen into the Dungeons of the Dead. Try again");
// You end the method here, so none of the rest of the code after this will execute
return;
}
Also, the fact that you do
else if (tre.isExit == true)
means that this won't execute if
tow.roomEnd == true
is also true. "Else if" means "if the current condition is true and the previous condition is false", so
if (A) {
// do work
}
else if (B) {
// Do work
}
is semantically equivalent to
if (A) {
// Do work
}
if (!A && B) {
// Do work
}
Finally, I mentioned this in passing, but I'd like to reiterate that it's not necessary to explicitly compare to true or false, so
if (tow.roomEnd == true)
should just be
if (tow.roomEnd)
Also, I don't think it makes sense for all of those conditions to be true at once. Can something actually be a room end, a dead end, and an exit at the same time? At a minimum, it seems like a particular location can't be both an exit and a dead end. If the data says that several of those things are true at once, it needs to be corrected in order for the program to function properly.
In every if statement you have keyword return;. The return statement terminates execution of the method and because of that only first Console.WriteLine is shown.
Read carefully: return (C# Reference)
Reading through what you've done, if I'm understanding this correctly what you're after is as follows.
public bool isExit;
public bool deadEnd;
public bool roomEnd;
tre.isExit = true;
dun.deadEnd = true;
tow.roomEnd = true;
if (dun.roomEnd == true)
{
Console.WriteLine("You've fallen into the Dungeons of the Dead. Try again");
}
else if (tow.roomEnd)
{
Console.WriteLine("You been caught by the Kings guard and have been placed in the tower for life.Try again");
}
else if (tre.isExit)
{
Console.WriteLine("You have found the treaure... now run!!");
}
else
{
Console.WriteLine("Too scared.....");
}
return
This will evaluate each condition individually, and then return once complete.
What this code is effectively saying is "if condition 1 is true, display the text and exit the if block, then return. Otherwise if condition 2 is true do the same, condition 3 / 4 do the same thing also.
I think this is what you're after at least. It could be refactored to make it a little simpler but don't have the time to go over that at the moment.
Assuming it is showing the Dungeons of the Dead and the Kings Guard message, you need to add an "else" to the if for tow.roomEnd.
I have a program that is completely functional, and I am now refactoring it. I am just in the process of learning c# so the original code was pretty terrible despite the fact that it ran just fine. One of the requirements of the program is that the user be able to return to the main menu at any point. I accomplished this as follows:
static bool bouncer = false
static void Exit(string input)
{
if (input == "\t")
{
bouncer = true
}
}
static string Prompt(string msg)
{
// takes input and passes it to Exit() then returns the input
}
static string FunctionA()
{
while(true)
{
if (bouncer == true)
{
break;
}
Prompt("whatever")
if (bouncer == true)
{
break;
}
Prompt("whatever")
if (bouncer == true)
{
break;
}
// return some stuff
}
}
static void Main()
{
bouncer = false
// writes the menu to console and handles UI
// FunctionA
{
The variable bouncer gets set to true if the user enters the "tab" character at any input point. The proliferation of break statement conditionals provides the structure that actually breaks out back to Main(). This is obviously not a very good solution and it makes the code hard to read.
Other attempts that I considered to accomplish the same task are:
Goto statement that jumps straight back to Main(). I scrapped this because goto has a very limited scope in c# and I don't think there is any good way to make it workable in this situation.
Calling Main() directly from Exit(). This is probably a bad idea, and I can't do it anyway because apparently Main() is "protected" in some way.
Using an event to react to TAB or ESC being pressed. It's unclear to me how I could use an event to do this since I still wouldn't be able to break right out of the event. My understanding is that the break statement has to actually be contained in the loop that needs to be broken as opposed to being written into a different function that is called from within the loop.
Any suggestions are greatly appreciated. I'm hoping there's something to be done with event handling or that I've overlooked something more simple. Thanks!
As a matter of coding style, the way it is works, but is seen as ugly. Unfortunately, if you need to break out immediately between sections of work, there is not a lot of ways around that.
You can change your current format of using breaks to using "if( bContinue ) { /* do next section of work */ }" control style. It changes the code from break out of the while loop to this:
static string FunctionA()
{
bool bContinue = true;
while( true == bContinue )
{
// Do initital work.
//
// Initial work can set bContinue to false if any error condition
// occurs.
if( true == bContinue )
{
// Do more work.
int returnCheck = MakeACall(); // Presume MakeACall returns negative interger values for error, 0 or positive values for success or success with condition/extra information.
if( 0 < returnCheck )
{
bContinue = false;
}
}
if( true == bContinue )
{
Prompt("whatever")
// Do more work.
bContinue = MakeASecondCall(); // Presume that MakeASecondCall returns true for success, false for error/failure
}
if( true == bContinue )
{
Prompt("whatever")
// Do more work.
// If error encountered, set bContinue to false.
}
if( true == bContinue )
{
Prompt("whatever else")
// Do more work.
// If error encountered, set bContinue to false.
}
// Done with loop, so drop out.
bContinue = false;
// return some stuff
}
}
Looking at your pseudo code, it reads like you only do a single pass through your work loop. If so, you can switch to a Do-While(false) format, and use the break to just drop to the bottom. Or, if you are only doing a single pass through your FunctionA, just do away with the While or Do-While control structure, and just use the if(true==bContinue){ /* Do more work */ }. It is not the cleanest of code, but when you perform long periods of serial work, you end up with such structures if you are not going to use a while or do-while for controlling the flow.
The disadvantage to using the if(bContinue){} style is that when an error condition occurs during the early stages of the process, the code does not exit out as quickly from the function as a break out of the while() or do-while() structure if the error occurs near the top of the work, as there will be the series of if statements that the code will test and then skip over. But it is readable, and if you use a descriptive name for your control variable (ie, nContinue or bContinue or workLoopControl) it should be fairly obvious that it is the master control flag for the function's work flow to whoever works or reviews the code after you.
Instead of an infinite loop and break statements, try using a conditional flag instead.
static void FunctionA()
{
bool done = false;
string response = string.Empty;
while (!done)
{
response = Prompt("whatever");
if(response == '\t')
{
done = true;
}
}
}
As a side note, I'm not sure why you have 'string' as the return type of several methods (e.g., 'FunctionA') when you aren't using the return value. That's why the code I gave above has it as 'void'.
I have added one label in form that is not visible to user.Base on the text that label contain proceed further.
Here is my logic,but it fail.I wanted like this,if label contain "No match" or "Time out",should not proceed.
If((!label.Text.Contain("No match")) || label.Text.Contain("Time out"))
{
// proceed further code
}
else
{
// code
}
Here Label contain "No match",then it move to else part that is right.But when label contain "Time out",then it go inside the if loop.So I modified code like this
If((!label.Text.Contain("No match")) || (!label.Text.Contain("Time out")))
{
// proceed further code
}
else
{
// code
}
still not working.If label contain "Time out",still it go into if loop not else loop.Label contain only one text at a time either "No match" or "Time out" or any other text.
I suspect you want:
if(!(label.Text.Contains("No match") || label.Text.Contains("Time out")))
{
// proceed further code
}
else
{
// code
}
Note the bracketing. The inner part is
label.Text.Contains("No match") || label.Text.Contains("Time out")
and then that's inverted. I would probably pull that out into a separate variable:
bool timedOutOrNoMatch = label.Text.Contains("No match") ||
label.Text.Contains("Time out");
if (!timedOutOrNoMatch)
{
}
else
{
}
Alternatively, invert the sense of it:
if (label.Text.Contains("No match") || label.Text.Contains("Time out"))
{
// Do whatever was in your else block.
}
else
{
// Do whatever was in your first block.
}
If your response to the "bad" labels is something that lets you return or throw an exception, this can also reduce the amount of nesting:
if (label.Text.Contains("No match") || label.Text.Contains("Time out"))
{
output.Text = "Go away";
return;
}
// Now handle the success case
Try with following code:
if(!(label.Text.Contains("No match") || label.Text.Contains("Time out")))
{
// proceed further code
}
else
{
// code
}
If you want to get right with your modified code, use AND operator:
if(!label.Text.Contains("No match") && !label.Text.Contains("Time out"))
{
// proceed further code
}
else
{
// code
}
To write your code in more understood form , you should write it in a way that it is readable and more understandable. I prefer to write this statement like this
bool ProceedFurther()
{
//Don't proceed if No Match
if(!label.Text.Contains("No match")) return false;
//Don't proceed if Time out
if(!label.Text.Contains("Time out")) return false;
//Proceed otherwise
return true;
}
and call ProceedFurther method at desired location.
If you really want only that statement, following is the best (mostly people forget to change || to && after they change the condition to negative (using !).
if(!label.Text.Contains("No match") && !label.Text.Contains("Time out"))
Look at this:
foreach(Object Item in comboBox1.Items)
{
if (Convert.ToString(Item) == Convert.ToString(dsGirasol.Tables["DatosGirasol"].Rows[contador][0]))
{
repetido = true;
break;
}
else
{
repetido = false;
}
}
Note that both of the possible outputs have a messagebox. However when I run this, nothing appears at all, and the rest of the code continues to run...
EDIT: Added the surrounding loop!
Why do you want the break there for? Try this:
if (Convert.ToString(Item) == Convert.ToString(dsMaiz.Tables["DatosMaiz"].Rows[contador][0]))
{
repetido = true;
MessageBox.Show("Encontre uno igual");
}
else
{
repetido = false;
MessageBox.Show("Encontre uno diferente");
}
Try evaluating the left and right parts of the condition before you evaluate the equality.
I can only imagine that it must be throwing an exception that is silently caught.
This will help you debug the issue.
eg:
var left = Convert.ToString(Item);
var right = Convert.ToString(dsMaiz.Tables["DatosMaiz"].Rows[contador][0]);
if (left == right)
{
...
}
else
{
...
}
EDIT:
Now that I see you are using a loop, go back to basics, is the loop even running?
Low tech debugging, check that there are some Items in the combobox and that you are referencing the combo you intended :)
Ok this is strange, I managed to solve the problem by puting each loop on a separate method, and now it works, thanks for the help anyways!