Tuesday, November 17, 2009

.NET Object Collections Using Generics 101

Since the .NET Framework 2.0, we have had the ability to use Generics from the System.Collection.Generic namespace to create a strongly typed list of objects. Some might be saying, "Well what is that?" It is a great way to take a single instance of an object and add it to a 'list' where additional object instances can be added as well. It is basically an ArrayList of objects.

So the next question might be, "Well why do I need that?" Think of another common way to organize relation data using a non-strongly type traditional DataSet. A DataTable within a DataTable has rows and columns. Typically to reference a value within that DataSet we might have a line of code similar to the following:

Dim MyValue As String = ds.Tables("MyTable1").Rows(0).Item("FirstName").ToString()

Now that does work, however that is a lot of hardcoding and can be difficult to keep up with. Especially on a multi developer project. Imaging trying to remember all of those column names if that DataSet was passed back to the UI to be bound to a control or populate others. This is where a nice entry point into a list of objects arises. Of course developers could comment on the several reasons using lists of objects is advantageous, but I will take the approach to a developer that is using native ADO.NET objects to do the same thing.

I will provide a simple example to help beginners understand how to put together a list of objects using the 'List(of T)' class. First let's start by looking at the following simple class named 'Customer':

Public Class Customer

Private mFirstName As String = String.Empty
Private mLastName As String = String.Empty
Private mID As Integer = 0

Public Sub New()
'Default class Constructor
End Sub

Public Property FirstName() As String
Return mFirstName
End Get
Set(ByVal value As String)
mFirstName = value
End Set
End Property

Public Property LastName() As String
Return mLastName
End Get
Set(ByVal value As String)
mLastName = value
End Set
End Property

Public Property ID() As Integer
Return mID
End Get
Set(ByVal value As Integer)
mID = value
End Set
End Property

Public Function ShowFullName() As String
'Simple class method; just for show
Return Me.FirstName + Me.LastName
End Function

End Class

Now at this point we may have received multiple rows back from the database containing data with the elements mapping to the properties above. Previously, we could have placed this data into a DataSet to pass back to the UI as mentioned before. This time we are going to build up a list of objects to use. Now in this case you may still have used an ADO.NET DataAdapter to get the data from a stored procedure and it is currently in a DataTable object. No problem, now is the time to place that data into an object instance (1 DataRow = 1 Object of type Customer) and then add that to the list. Let's take a look how that is done below:

'Create an Customer Object
Dim MyCustomer As New Customer()
'Create a List of objects of type Customer
Dim MyCustomerLst As New List(Of Customer)
'Iterate through the data returned in the DataTable
For Each dr As DataRow In dt.Rows

'Create a new instance of the Customer object to place this iterations values
MyCustomer = New Customer()

'Add the data to the object's properties
If Not IsDBNull(dr("FirstName")) Then MyCustomer.FirstName = dr("FirstName")
If Not IsDBNull(dr("LastName")) Then MyCustomer.LastName = dr("LastName")
If Not IsDBNull(dr("CustomerID")) Then MyCustomer.ID = dr("CustomerID")

'Add the single object instance created above to the 'List' of objects

At this point the object collection named 'MyCustomer' can be passed around your application's layers as a type of 'List(of Customer)'. For example take a look to the following method that takes the list as a parameter, and then loops through it to use its values:

Public Function GenerateCustomerList(ByVal CustomerLst As List(Of Customer)) As String

Dim sb As New StringBuilder

'Iterate through each 'Customer' object instance in the List(of Customer) passed into method:
For Each SingleCustomer As Customer In CustomerLst

'Build a String in the format of: John Smith ID: 1234
sb.AppendLine(SingleCustomer.FirstName + " " + SingleCustomer.LastName + " ID: " + SingleCustomer.ID.ToString())


'Return the appended String
Return sb.ToString()

End Function

So as you can see we were able to iterate through the object collection and being able to refer to the values by object property name rather than a hardcoded value representing the original column named returned from the database. One might say in the example above that we did at one point reference the column name when adding the data to the 'Customer' object instance. Yes, that is true but with this methodology you need only to reference it once and the location of that reference is typically at a low level either in the DAL or at the bottom of the BLL depending on your design. Therefore, if there were database changes that affected those names, they could be changed in one place rather than scattered throughout the UI and entire application.

Passing around a list of objects is much preferable to passing around traditional ADO.NET objects in many situations. Also, there are other types that may have been used similarly that could also be replaced using object collections. An example could be an Array or ArrayList. In fact performance wise, object collections are very good. Read the following excerpt from the MSDN:

"In deciding whether to use the List(Of(T)) or ArrayList class, both of which have similar functionality, remember that the List(Of(T)) class performs better in most cases and is type safe."

There are so many uses for a list of objects, and this entry was just to describe one usage and to provide the developer new to using the List(of T) class some ideas on how they may expand on it. Once you begin to harness the power of OOP and the basic component of it: the class, you will discover an entire new set of powerful tools the .NET Framework offers as discussed here using a List(of Customer).

***UPDATE*** You can imporve this code one step further by using LINQ to populate the list of objects directly rather than manually looping through each DataRow. To see the code look the post of mine from the link below:

How To: Populate a List of Objects from a DataSet Using LINQ


  1. Hello Sir,
    Thanks for your such great article.
    But i have some doubt i hope you help me to solve them.

    In your example you have shown about data fetching from database. But i am little bit worried what if my data is having more than 1000 rows looping and adding on object will take time than filling dataset.

    One more thing in .NET 2.0 microsoft have improved data adapter and dataset. so if i use this property class structure you shown, Then when i save my records more than 1000 i need to create number of commands instead i can use dataset.update and updatebatchsize will make it update in one roundtrip.

    Please clear my confusion sir.

  2. In your concern about looping etc. you can see that I actually already populated a DataSet (actually DataTable) before inserting the data into the object collection. The reason for mapping the data from the dataset to the object collection is because it is typically easier to work with objects that are strongly typed rather than raw DataSets. One improvement to this article that I just updated with the URL is to use LINQ to populate the list of objects rather than having to manually loop through all datarows individually. Take a look here:

    How To: Populate a List of Objects from a DataSet Using LINQ

  3. Thank you! Business Objects (classes) are MUCH FASTER than Datatables to pass around. Lifesaver!

  4. Thanks for the positive feedback and I am glad it helped! Getting away from raw ADO.NET objects and understanding OOP concepts with Business Objects at the core is a real eye opener. It really opens the door to a much more organized and consistent design of applications when Business Objects are used.

  5. The purpose for applying the information from the dataset to the item selection is because it is generally simpler to perform with things that are highly entered rather than row DataSets.