I'll start by saying that i am no beginner in C# but not very much more and need help returning value to main. Or rather tell me what is the "correct" way.
I want to return a fail value (simply -1) from the application, in case of any exception and ending up in a catch. In that case passing info to main to return -1.
The way I solved it was by just adding a static global variable mainReturnValue (to be able to access it from main), and setting its value to -1 in the catches.
Is that a correct way of doing it, based on my current code?
If anyone is wondering the applications is executed without user interaction and that's why I need to catch the exit state. The form/GUI just displays info about the progress, in case it's started manually.
namespace ApplicationName
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{ ...
static int mainReturnValue = 0; //the return var
static int Main(string[] args)
{
Application.Run(new Form1(args));
return mainReturnValue; //returning 0 or -1 before exit
}
private void Form1_Load(object sender, System.EventArgs e)
{
the code..in turn also calling some sub functions such as DoExportData...and I want to be able to return the value to main from any function...
}
private int DoExportData(DataRow dr, string cmdText)
{
try { ... }
catch
{ mainReturnValue = -1; }
}
Thanks.
You could do this:
static int Main(string[] args)
{
Form1 form1 = new Form1(args);
Application.Run(form1);
return form1.Result;
}
and then define a property on your Form1 class, whose value you can set after the DoExportData method executes. For example:
public int Result { get; private set; }
private void Form1_Load(object sender, System.EventArgs e)
{
Result = DoExportData(...);
}
private int DoExportData(DataRow dr, string cmdText)
{
try
{
...
return 0;
}
catch
{
return -1;
}
}
How to: Get and Set the Application Exit Code from MSDN.
By the way, an exit code of 0 indicates success, while anything > 0 indicates an error.
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