How to Exit a Method without Exiting the Program?
Solution 1:
There are two ways to exit a method early (without quitting the program):
- Use the
return
keyword. - Throw an exception.
Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.
If your method returns void then you can write return without a value:
return;
Specifically about your code:
- There is no need to write the same test three times. All those conditions are equivalent.
-
You should also use curly braces when you write an if statement so that it is clear which statements are inside the body of the if statement:
if (textBox1.Text == String.Empty) { textBox3.Text += "[-] Listbox is Empty!!!!\r\n"; } return; // Are you sure you want the return to be here??
If you are using .NET 4 there is a useful method that depending on your requirements you might want to consider using here: String.IsNullOrWhitespace.
- You might want to use
Environment.Newline
instead of"\r\n"
. - You might want to consider another way to display invalid input other than writing messages to a text box.
Solution 2:
In addition to Mark's answer, you also need to be aware of scope, which (as in C/C++) is specified using braces. So:
if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;
will always return at that point. However:
if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0)
{
textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
return;
}
will only return if it goes into that if
statement.
Solution 3:
I would use return null;
to indicate that there is no data to be returned
Solution 4:
The basic problem here is that you are mistaking System.Environment.Exit
for return
.