Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Simple OleDbDataReader question (ADO.NET)

Options
  • 08-07-2003 4:11pm
    #1
    Registered Users Posts: 7,468 ✭✭✭


    Folks
    I am creating the above object in code and want to close it within a finally block, but its throwing an error e.g*:
    OleDbDataReader dr;
    try
    {
    	commandObject.CommandText = "SELECT * FROM Employees";
    	dr = commandObject.ExecuteReader();
    	while (dr.Read())
    	{
    		...
    	}
    }
    catch (Exception e)
    {
    	...
    }
    finally
    {
    	if (dr!=null) // ERROR OCCURS HERE
    	{
    		dr.Close() 
    	}
    }
    
    

    Now the compiler is returning an error because dr is not initialised, obviously, but I don't want to initialise it outside of the try block. What I can do is close the DataReader at the end of try, but as I said I would rather do it from within finally (or catch) in case of any errors.

    Does anybody know of a way I can do this without initialising the datareader outside of try?



    *Not the actual code, probably full of errors


Comments

  • Closed Accounts Posts: 9,314 ✭✭✭Talliesin


    You could have an unmanaged block with a pointer. Initialise the pointer to 0. Set the pointer to point to the object when you create it. Examine the pointer in the finally block.

    This is an example of garbage collection making code more difficult. If you have either automatic deletion of local objects or reference-count based garbage collection you could rely on the destructor calling close() at the correct time.


  • Registered Users Posts: 15,443 ✭✭✭✭bonkey


    Originally posted by Evil Phil
    Does anybody know of a way I can do this without initialising the datareader outside of try?

    Not readily.
    At the risk of asking a stupid question, why would you be averse to initialising it to null?
    OleDbDataReader dr = null;
    

    Is there some risk/high cost in doing so that would be worth the effort of going through additional contortions to try and avoid it?


    jc


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    Originally posted by bonkey
    OleDbDataReader dr = null;
    

    Works a treat. I never thought of something so simple :rolleyes:


Advertisement