Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I implement IDisposable here?

My method which calls SQL Server returns a DataReader but because of what I need to do - which is return the DataReader to the calling method which resides in a page code-behind - I can't close the connection in the class of the method which calls SQL server. Due to this, I have no finally or using blocks.

Is the correct way of disposing resources to make the class implement IDisposable? Alternatively should I explicitly dispose the unmanaged resource (class-level fields) from the caller?

EDIT: I send the datareader back because I need to bind specific data from the datareader to a listitem control, so in the calling class (Codebehind page), I do:

 new ListItem(datareader["dc"]); (along those lines).
like image 841
GurdeepS Avatar asked May 19 '10 16:05

GurdeepS


2 Answers

I would say yes, implement IDisposable. One of the main reasons as far as I can tell to use it is when you cannot trust the user of the object enough to do it properly themselves. This seems to be a prime candidate for that.

This being said however, there is a question to your architecture. Why is it that you want to send the DataReader itself to the page instead of calling a method to do it for you (including the relevant cleanup) by returning what is necessary? If it necessary to give the actual reader to the page, then so be it.

like image 89
Kyle Rosendo Avatar answered Oct 20 '22 12:10

Kyle Rosendo


Holding the database connection as a member variable in your reader class and making your reader class implement IDisposable seems fine to me.

However, you might consider making your method return IEnumerable and using yield return statements to walk through the data reader. That way you can return the results and still clean up from within your method.

Here's a rough sketch of what I mean:

public IEnumerable<Person> ReadPeople(string name)
{
    using (var reader = OpenReader(...))
    {
        // loop through the reader and create Person objects
        for ...
        {
            var person = new Person();
            ...
            yield return person;
        }
    }
}
like image 43
Don Kirkby Avatar answered Oct 20 '22 13:10

Don Kirkby