locked
Why Is The Compiler Issuing an Error When An Out Parameter is Passed to Another Function as an Out Parameter? RRS feed

  • Question

  • Visual Studio 2010
    C#

    Code:

            public void GetFunctions(UInt32 vnFunction, out bool[] rbFunctions)
            {
                //  Wrapper for the SQLGetFunctiosn API
    
                try
                {
                    SQLReturnCodes nSQLResults = Win32APISQL.SQLGetFunctions(hdbc, (short)vnFunction, out rbFunctions);
                    if (SQLReturnCodes.SQL_SUCCESS != nSQLResults)
                        CheckError("SQLGetFunctions: ", nSQLResults);
                }
                catch
                {
                    int err = Marshal.GetLastWin32Error();
                    // throw new Win32Exception(err);
                    MessageBoxResult result = MessageBox.Show(err.ToString(), "ODBC 32", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

    Where SQLGetFuncions is defined as:

            [DllImport("odbc32.dll", SetLastError = true)]
            public static extern SQLReturnCodes SQLGetFunctions(IntPtr hdbc, short fDirection,out bool[] pfExists);

    The compiler generates the following error:
    The out parameter 'rbFunctions' must be assigned to before control leaves the current method

    


    http://www.saberman.com

    Wednesday, February 15, 2012 6:00 PM

Answers

  • The problem is that your try/catch creates a code path where the rbFunctions variable may not be set, but the method doesn't exit via an exception.

    You can work around this by explicitly throwing an exception in your catch, or by setting the value in your catch statement, ie:

     
          catch
                {
                    int err = Marshal.GetLastWin32Error();
                    // throw new Win32Exception(err);
                    MessageBoxResult result = MessageBox.Show(err.ToString(), "ODBC 32", MessageBoxButton.OK, MessageBoxImage.Error);
                    rbFunctions = null; // Set this for this code path
                }


    Reed Copsey, Jr. - http://reedcopsey.com
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".

    • Marked as answer by saberman Wednesday, February 15, 2012 10:05 PM
    Wednesday, February 15, 2012 6:24 PM