I’m designing a library that connects to a data source (similar to a DB) and returns various POCO objects.
I’m using the datasource vendors .NET library to make the connection (and retrieve the objects), which I’m then converting into my much lighter POCO objects. To build these POCO objects, I have a static method on each POCO class (.FromDBObject(DBObject obj) that takes the DB object and returns a new POCO instance.
The initial connection to the DB isn’t fast so it’s not something I want to be doing on the fly (per POCO build), so I’m wrapping a library around it that manages the connection to limit this slowdown, as well as dispose of the connection correctly.
As part of this library, I have a number of methods that return lists of my POCO’s. One ‘oddity’ of the DB objects is that they aren’t loaded into memory when the vendor library loads them, they require an open connection to load their data.
As a result, if I return an IEnumerable<POCO> then it’s possible that the connection could be closed (time/dispose) before this has been enumerated, thus crashing when creating the POCO’s.
So a long set up for a short question.
- Should I return
IEnumerable<POCO>but in the actual method perform a.ToList()to force the instantiation or should I specify the return type asList<POCO>?
Your method return type should have little bearing on your data access. Determine whether you want to return an
IEnumerableor aListfirst. IfIEnumerableis sufficient, then use aToList().If you need the extra methods that
Listprovides, then returningListis fine since it does an implicitToList()call, although I would explicitly callToList()anyway just to make it clear that you want load the data from the database at that point in the code.