.NET Tips and Tricks

Blog archive

Initialize Any Collection, Including Your Own, in One VB Statement

Most Visual Basic developers are aware that they can declare and initialize an array in one statement like this:

Dim  csts() As String = {"A123", "B456"}

What you may not know is that, as of Visual Basic 10 (.NET Framework 4/Visual Studio 2010), there's a variation on that syntax you can use to initialize collection: Just insert the keyword From between your collection declaration and the initialization list (the stuff in the curly braces).

For instance, this code initializes a List of Customer objects (each Customer object is defined by passing a CustomerID when creating the Customer object):

Dim  csts As New List(Of Customer) From 
  {New Customer("A123"), New  Customer("B456")}

This example does the same thing, but calls a factory method that returns Customer objects

Dim  csts As New List(Of Customer) From 
  {CustomerFactory.GetCustomerById("A123"), 
  CustomerFactory.GetCustomerById("A456")}

To initialize a Dictionary that uses strings for its keys and Customer objects for its values, all you need is a few more curly braces to mark off each item in the list:

Dim  csts As New Dictionary(Of String, Customer) From 
{{"A123", New Customer("A123")}, {"A456", New Customer("A456")}}

The From keyword can be used with any collection that implements the IEnumerable interface (or has a GetEnumerator method), and has an Add method that can use the From keyword. The From keyword uses the IEnumerable interface as evidence that the object is a collection, and then calls the Add method for each item in the initializer list.

If you're creating your own collection class, you can let developers use the From keyword with your class by implementing the IEnumerable interface and having a method called Add that accepts a single parameter (or however many parameters each item in your collection requires).

If you're working with a collection that doesn't have an Add method, you don't have to rewrite the collection class; just create an extension method for the class that puts new items in the collection, and call that method Add. This extension works with the Queue class to give it the ability to use the From initializer syntax by wrapping its Enqueue method inside an Add method:

Module  PHVExtensions
  <Runtime.CompilerServices.Extension()> 
  Sub Add (ByVal q As Queue, ByVal itm As Object)
    q.Enqueue(itm)
  End Sub

End Module

Posted by Peter Vogel on 02/21/2013


comments powered by Disqus

Featured

Subscribe on YouTube