#1,022 – How to Use Return Values from All Delegate Instances

If a delegate instance has an invocation list with multiple methods and you invoke the delegate using the standard functional notation, you’ll get back the return value only for the last method in the invocation list.

If you want to consume the return value for each method in a delegate’s invocation list, you can use GetInvocationList to explicitly iterate through the invocation list.

            ReturnIntDelegate del1 = Method1; // Returns 12
            del1 += Method2;  // Returns 99

            // Invoke all at once, get return value
            // only from last
            Console.WriteLine("Invoke normally");
            int val = del1();
            Console.WriteLine(val);

            // Invoke one at a time
            Console.WriteLine("Invoke one at a time");
            foreach (ReturnIntDelegate del in del1.GetInvocationList())
            {
                int ret = del.Invoke();
                Console.WriteLine(ret);
            }

1022-001

Advertisement

#10 – The Return Value from Main() Sets ERRORLEVEL Variable in Windows

If your Main() function returns an integer value, you can check that value in the calling program or script using the ERRORLEVEL environment variable.  By convention, a return value of 0 indicates success and any other value indicates an error.  Below is a sample .bat file that calls a program called MyProgram and then checks the return value.

@echo off

MyProgram

IF "%ERRORLEVEL%" == "0" goto OK

:NotGood
    echo Bad news.  Program returned %ERRORLEVEL%
    goto End

:OK
    echo Everything A-OK

:End

#8 – The Main() Function Can Return an int

Instead of returning void, Main() can return an integer value, which can then be read by the calling program or script.  Notice that the return type of the function is an int

class Program
{
    static int Main()
    {
        Console.WriteLine("Doing something..");

        if (DateTime.Today.DayOfWeek == DayOfWeek.Monday)
            return -1;     // Monday is bad
        else
            return 0;
    }
}