Reasons to Move from DataTables to Generic Collections
These days, no community member writes or speaks about using
DataTables and DataSets for data operations. But, there are a number of
real projects built using them, and many developers still feel happy when
they use them in their projects. Sometimes it is not easy to completely
replace DataTables with typed generic lists, particularly in bulky
projects. But now is the right time to move, as future developers may not
even learn about DataTables :).
Generic collections have a number of advantages over DataTables. One cannot imagine a day without generic collections once he/she gets to know how beneficial they are. The following is a list of the reasons to move from DataTables to collections that I could think of now:
- DataTable stores boxed objects, and one needs to unbox values when needed. This adds overhead on the runtime environment. However, values in generic collections are strongly typed, so no boxing involved.
- Unboxing happens at runtime, as does the type checking. If there is a mismatch between types of source and target, it leads to a runtime exception. This may lead to a number of issues while using DataTables. In case of collections, as the types are checked at the compile time, such type mismatches are caught during compilation.
- .NET languages got very nice support for creating collections, like object initializer and collection initializer. We don’t have such features for DataTables.
- LINQ queries can be used on both DataTables and collections. But the experience of writing the queries on generic collections is better because of IntelliSense support provided by Visual Studio.
- DataTables are framework specific; we often see issues with serializing and de-serializing them in web services. Generic collections are easier to serialize and de-serialize, so they can be easily used in any service and consumed from a client written in any language.
- ORMs are becoming increasingly popular, and they use generic collections for all data operations.
- Mocking DataTables in unit tests is a pain, as it involves creating the structure of the table wherever needed. But a generic collection needs a class defined just once.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)