March 5, 2021
Hot Topics:

Declaring Anonymous Types in VB

  • By Paul Kimmel
  • Send Email »
  • More Articles »


Using an anonymous type means that the compiler will code generate a class for you based on context and named initializers. This article introduces you to anonymous types and explores some of the variations of their usage.

I am not lazy by nature; the converse is actually true. I personally spend hundreds even thousands of hours at my craft, but when it comes to solving problems time is money. When I'm learning then I don't mind tickling an idea to determine all of the myriad of ways in which it can be solved. In practice I use the cheapest, most direct, and practical approach that meets this test: reasonableness and sufficiency.

I write a dozen classes a week. I re-write some classes over and over throughout the years to discover the optimal solution. In practice though I borrow my own code, the code of others, or use code generators and tools to get the job done. Some 'bosses' may want to feel that we programmers are working hard, but the smart boss will want you to work smarter not harder. Working smarter means that you leverage all of the tools and resources available for optimal results. In Visual Basic, in some contexts, anonymous types provide reasonable and sufficient solutions and satisfy the optimal use of time.

Defining an Anonymous Type

An anonymous type quite simply means that you don't specify a class ahead of time. All you do when you use an anonymous type is to specify the named fields and values; the compiler then writes the class for you. Letting the compiler write your classes is a great labor saver. Imagine no syntax errors, no class to debug, and being left with usable results.

If you interviewed the inventor of anonymous types and asked why were these invented you might get a variety of answers. One answer might be anonymous types help when you are using LINQ. A simple answer plain for all to see is that for years programmers had to specify every single class by hand and this is labor intensive. Clearly many classes have historically been written and may only be used one time. Suppose for example that you have a customer and contact information class. Further suppose that you want to display a customer name and phone number to display this information in a pick list or report. Some programmers-including me in the past-have defined a composite class with containing the desired bits of information. Accumulatively all of these kinds of classes add up to a significant amount of time over a project and career. The anonymous type-and technologies like LINQ-eliminate the need to write these kinds of classes.

An anonymous type is defined by using the Dim keyword, a variable name, followed by the assignment operator, the New With construct, and a list of field names and values. Think of it as stenography for programmers. Here is a very short anonymous type definition that defines a simple company class.

Dim company = New With { .CustomerID = "ALFKI", .CompanyName = "Alfreds 

When the compiler encounters the preceding code it interprets this code as you wanting a class and code. It then generates one for you. From this point you can use the object company and modify CustomerID and CompanyName just as if you had written the class yourself.

Note: CodeRush is a meta-programming tool that writes code using pre-existing templates and a two or three shortcut key combination.

Arguably you could use a great tool like CodeRush and the labor involved in writing the class yourself is less labor intensive than writing all of the code keystroke by keystroke, but think of the anonymous types as and an evolutionary progression from manually writing the code-to using meta-programming tools CodeRush-to using a shorter notation. (A neat benefit of CodeRush is of course that you can iteratively define new CodeRush templates that spit out user-defined templates. This means now that the anonymous type exists and you can define a CodeRush template for it. In this way programmers, learning new idioms and using tools like CodeRush can stay hyper-productive.)

The anonymous type shown earlier generates a class as if you had written it yourself. You can verify this with a tool like Red-Gate's Reflector. Here is the long-hand version of the customer class, but really who wants to go to all the trouble for every single class (see Listing 1).

  Public Class Customer
          Public Sub New()
          End Sub
          Public Sub New(ByVal CustomerID As String)
              FCustomerID = CustomerID
          End Sub
          Private FCustomerID As String
          Public Property CustomerID() As String
                  Return FCustomerID
              End Get
              Set(ByVal Value As String)
                  FCustomerID = Value
              End Set
          End Property
          Private FCompanyName As String
          Public Property CompanyName() As String
                  Return FCompanyName
              End Get
              Set(ByVal Value As String)
                  FCompanyName = Value
              End Set
          End Property
          Public Overrides Function ToString() As String
              Return String.Format("CustomerID={0}, CompanyName={1}", _
                                   FCustomerID, FCompanyName)
          End Function
      End Class

Listing 1: The Customer class long-hand.

There are benefits to anonymous types in addition to saving you time. For instance, every application is comprised of classes. These classes make up the model that represents your system. The more classes there are the more complex your model is. You don't have to model anonymous types. Generally anonymous types are temporal. Excluding piddling classes from your system--or the model of your system--makes it easier for other developers to jump on board more quickly. And, if you are working on a disciplined team then of course classes you don't write save you time managing the model of your system. Saving time writing, modeling, and learning a system saves a significant amount of time accumulatively.

Page 1 of 2

This article was originally published on December 7, 2009

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date