Introduction
This approach helps us not to customize our Data Access Layer for different types of data classes. Consider we have some "Data class" in our application, and we want the data class to act as a collection. Generally, what we do is declare a "Generic List" (New feature in 2.0) of that data class type and populate our data list from the database. For populating the list, we loop through the data class with customized code and add the class to our list collection. This will be tedious and time-consuming if we have hundreds of classes where we need to rewrite the same code again and again.
To avoid that, I have conceived a new approach where we can pass the object of the class as a parameter, and as an output, we get a Generic Data List. Then we can typecast the Generic list back to our custom List collection. This is accomplished using reflection.
In the below example, I will explain how to do it, considering we have a data class called Person.
Data Class Person Data Object
In UI, create the instance of the Data object and pass it to the method "ExecuteGenericList". ExecuteGenericList method process the passed object and creates a collection of the object depending on the number of rows we get from our select query. A little bit of type casting has to be done to the returned Generic List to convert it to our typed data list Person.
Our DAL class "ExecuteGenericList" uses reflection to iterate through all the properties of the class and creates a generic list collection for each and every row.
DAL, Where our object is read and returned as a List.
Download Source code to see the worked out example.