//#define WITH_DATA_NOT_INITIALIZED
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace DemoOutParam
{
    class Program
    {
        static void Main( string[ ] args )
        {
#if WITH_DATA_NOT_INITIALIZED
            int data;
#else
            var data = 0;
#endif

            try
            {
                GetDataAndThrow( out data );
                #if WITH_DATA_NOT_INITIALIZED
                #else
                    Console.WriteLine( "Data variable is {0}", data );
                #endif
            }
            catch( Exception )
            {
                Console.WriteLine( "Exception occured.");
            }

            // What value will have the data field?
            #if WITH_DATA_NOT_INITIALIZED
                // If the code tries to access the data variable,
                // the compiler issues CS0165.
            #else
                Console.WriteLine( "Data variable is {0}", data );
            #endif
        }

        private static void GetDataAndThrow( out int data )
        {
            // Do not set a value for the required out parameter, but throw an
            // exception.
            throw new Exception( "Data cannot be set");
        }
    }
}

Advertisements