I am still pretty new to C# and am having a difficult time getting used to it compared to C/CPP.
How do you exit a function on C# without exiting the program like this function would?
if (textBox1.Text == "" || textBox1.Text == String.Empty || textBox1.TextLength == 0) textBox3.Text += "[-] Listbox is Empty!!!!\r\n"; System.Environment.Exit(0);
This will not allow return types and if left alone it will keep going on through the function unstopped. Which is undesirable.
Exit a Java Method using Return exit() method in java is the simplest way to terminate the program in abnormal conditions. There is one more way to exit the java program using return keyword. return keyword completes execution of the method when used and returns the value from the function.
In python, we have an in-built quit() function which is used to exit a python program. When it encounters the quit() function in the system, it terminates the execution of the program completely.
There are two ways to exit a method early (without quitting the program):
return
keyword.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:
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.
Environment.Newline
instead of "\r\n"
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With