Search code examples
c#.netidisposableusing

Is is right to return a method inside a "using(object that implements iDisposable)" statment?


Possible Duplicate:
If I return a value inside a using block in a method, does the using dispose of the object before the return?

I have this code (simplyfied):

bool method1()
{
      using (OleDbConnection con = new OleDbConnection(connString))
            {
                bool b = false;

                try
                {
                    con.Open();
                    b = true;

                }
                catch (Exception)
                {
                    b = false;
                }
                finally
                {
                    con.Close();
                    return b;
                }                
            }
}

I return before the closing curly bracket of the "using" statment. Does my object "con" gets Disposed anyway? Is is better to use the following code?:

bool method1()
{
      bool b = false;
      using (OleDbConnection con = new OleDbConnection(connString))
            {
                try
                {
                    con.Open();
                    b = true;

                }
                catch (Exception)
                {
                    b = false;
                }
                finally
                {
                    con.Close();                    
                }                
            }

        return b;
}

Solution

  • using expands into somewhat more complex with additional if statement like

    OleDbConnection con = new OleDbConnection(connString)
    try
    {
        con.Open();
    }
    finally
    {
        // Check for a null resource.
        if (con != null)
            // Call the object's Dispose method.
            ((IDisposable)con).Dispose();
    }  
    

    So in your example you might get NullReferenceException in finally block.

    So if you want to return the status of operation and Dispose and object, I suggest to use this code snippet

    using(OleDbConnection con = new OleDbConnection(connString))
    {
        try
        {
            con.Open();
            return true;
        }catch(OleDbException ex)
        {
            //log error
            return false;
        }
    }