Deborah's Developer MindScape

         Tips and Techniques for Web and .NET developers.

August 19, 2009

Anonymous Types: An Introduction

Filed under: C#,Lambda Expressions,LINQ,VB.NET @ 2:31 pm

The last several posts have provided examples of using anonymous types. This post backs up a little and provides an introduction if you are not already familiar with anonymous types.

If you are familiar with anonymous types and are looking for  more examples, check out these links:

Anonymous types are new in C# 3.0 and VB 9.0 (Visual Studio 2008). An anonymous type allows you to encapsulate a set of properties (not methods) into a specific object without explicitly defining a type.

When you create a class, such as a Customer class, you are explicitly creating a Customer type with defined properties and methods. The resulting class defines a Customer type which is a named type with the name Customer.

There are times, however, where you need a temporary type. You could explicitly create this type using a class, but that seems like overkill if you only plan to use the type within one routine. This is where an anonymous type is very useful.

It is important to note that the properties of an anonymous type are read/write in VB, but read-only in C#.

You can create an anonymous type manually using the following syntax.

In C#:

var stats = new {Name = String.Empty, Max = 0,
                 Min = 0, Ave = 0};

In VB:

Dim stats = New With {.Name = String.Empty, .Max = 0, _
                      .Min = 0, .Ave = 0}

This code creates an anonymous type with Name, Max, Min, and Ave properties. This anonymous type defines some statistics. For example, a list of students each have a set of scores for a class. This anonymous type provides the student’s name and score statistics.

However, using the syntax in this example is not the usual way to create anonymous types. Rather, the most common technique for creating anonymous types is within a Linq statement.

In C#:

var scoreQuery = from Student s in Students
             select new  {Name = s.LastName,
                          Max = s.Scores.Max(),
                          Min = s.Scores.Min(),
                          Ave = s.Scores.Average()};
foreach (var s in scoreQuery)
    Debug.Print("Student Name: {0}", s.Name);
    Debug.Print("Min: {0}, Max: {1}, Ave: {2}", s.Max, s.Min, s.Ave);

In VB:

Dim scoreQuery = From s As Student In Students _
             Select New With {.Name = s.LastName, _
                              .Max = s.Scores.Max(), _
                              .Min = s.Scores.Min(), _
                              .Ave = s.Scores.Average()}
For Each s In scoreQuery
    Debug.Print("Student Name: {0}", s.Name)
    Debug.Print("Min: {0}, Max: {1}, Ave: {2}", s.Max, s.Min, s.Ave)

NOTE: This code assumes you have a Student class with LastName and Scores properties (see below) and a populated List<Student> with several students and their scores.

The Linq statement in this example processes each student in the list of students. For each student, it creates an instance of the anonymous type with the student’s name and the appropriate statistics.

The for/each loops through the resulting set of anonymous types and displays the results.

In my example, the results are as follows:

Student Name: Baggins
Min: 97, Max: 65, Ave: 87.2
Student Name: Cotton
Min: 100, Max: 90, Ave: 93.6
Student Name: Brandybuck
Min: 88, Max: 65, Ave: 79.6

Here is the minimum code for the Student class used in this example:

In C#:

public class Student
    public string LastName { get; set; }
    public List<int> Scores { get; set; }

In VB:

Public Class Student
    Private _LastName As String
    Public Property LastName() As String
            Return _LastName
        End Get
        Set(ByVal value As String)
            _LastName = value
        End Set
    End Property

    Private _Scores As List(Of Integer)
    Public Property Scores() As List(Of Integer)
            Return _Scores
        End Get
        Set(ByVal value As List(Of Integer))
            _Scores = value
        End Set
    End Property

End Class

Anyone else found interesting ways to use anonymous types? I’d enjoy hearing about it…



  1.   Waleed El-Badry — August 21, 2009 @ 9:28 am    Reply

    Thanks Deborah for your recurring contribution. You are priceless to Visual Basic community.

  2.   Cliff Jacobson — August 21, 2009 @ 2:47 pm    Reply

    One small typo, this feature was available with Visual Studio 2008 which shipped with .NET 3.5 which includes C# 3.0 and VB 9.0.

    For Visual Studio 2010 and .NET 4.0 there is going to be C# 4.0 and VB 10.0.

  3.   DeborahK — August 21, 2009 @ 3:45 pm    Reply

    Hi Cliff –

    You are correct.

    I have been working on VS 2010 articles and typed “2010” here when it is “2008”. I correct the text.


  4.   Gizi Ben-Tovim — August 28, 2009 @ 4:51 pm    Reply

    Thanks Deborah for these very helpful tips and code sections.
    Also, this is one of the few expert blogs where VB programmers are not ignored!

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2022 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs