Anonymous Types: An Introduction

Posted Wed, Aug 19 2009 12:31 by Deborah Kurata

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)
Next

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
        Get
            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)
        Get
            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…

Enjoy!

Filed under: , , , , ,

Comments

# Microsoft spotlight: MVP Deborah Kurata

Wednesday, August 19, 2009 6:55 PM by No1 Microsoft Fan

I’ve been keeping an eye on Deborah’s MSMVPS blog and am amazed. Deborah is posting some awesome code

# Interesting Finds: August 20, 2009

Thursday, August 20, 2009 6:41 AM by Jason Haley

Interesting Finds: August 20, 2009

# Anonymous Types: An Introduction - Deborah Kurata

Thursday, August 20, 2009 9:47 AM by DotNetShoutout

Thank you for submitting this cool story - Trackback from DotNetShoutout

# re: Anonymous Types: An Introduction

Friday, August 21, 2009 9:28 AM by Waleed El-Badry

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

# re: Anonymous Types: An Introduction

Friday, August 21, 2009 2:47 PM by Cliff Jacobson

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.

# re: Anonymous Types: An Introduction

Friday, August 21, 2009 3:45 PM by Deborah Kurata

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.

Thanks!

# Wonderful blog

Friday, August 28, 2009 4:51 PM by Gizi Ben-Tovim

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!

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: