Click here to Skip to main content
6,594,932 members and growing! (15,841 online)
Email Password   helpLost your password?
Languages » VB.NET » Visual Basic .NET     Beginner License: The Code Project Open License (CPOL)

Object Initialization Expressions and Anonymous Types in Visual Basic 9.0

By Alessandro Del Sole

An introduction to some new cool features of the Visual Basic 9.0 language syntax.
VB 7.x, VB 8.0, VB 9.0, VB 6, .NET, Dev
Version:2 (See All)
Posted:9 Mar 2008
Views:7,180
Bookmarked:7 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
1 vote for this article.
Popularity: 0.00 Rating: 2.00 out of 5

1
1 vote, 100.0%
2

3

4

5

Introduction

Visual Basic 9.0 introduces some new language features like Object Initializers and Anonymous Types. These features are really important to understand if you plan to learn LINQ, the major new feature in .NET Framework 3.5.

In this article, I will introduce Object Initializers and Anonymous Types in Visual Basic 2008, providing some code snippets to make the concepts clearer.

You are free to use Visual Basic 2008 Express Edition or greater, since the compiler is always the same.

Object Initialization Expressions

Object Initialization Expressions is about instantiating objects whose constructors receive no arguments even if objects themselves expose one or more property which can be initialized. To accomplish this, in Visual Basic 9.0, we can use the With keyword. Consider the following, very simple, Person class which exposes two properties, Name and Surname:

Class Person

    Private _name As String
    Private _surName As String

    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal value As String)
            _name = value
        End Set
    End Property

    Public Property SurName() As String
        Get
            Return _surName
        End Get
        Set(ByVal value As String)
            _surName = value
        End Set
    End Property
End Class

As you can see, no explicit constructor has been specified. This means that the class implements a constructor that does not receive any arguments. To instantiate this class using Visual Basic 8.0, we have to write the following code:

Dim p As New Person

With p
     .Name = "Alessandro"
     .SurName = "Del Sole"
End With

Now, in Visual Basic 9.0, we can use the following syntax:

'Object Initialization Expression
Dim p As New Person With {.Name = "Alessandro", .SurName = "Del Sole"}

This is very useful both for writing less lines of code and for keeping the code clearer. Many WPF objects have constructors that receive no arguments, so this is another good chance to instantiate objects in the base class library.

Anonymous Types

Another new interesting feature of the .NET Framework 3.5 is in the so called Anonymous Types. Substantially, when you instantiate an object, you don’t need to specify its type but you can populate it with elements of your own interest. This must not be confused with the Local Type Inference, another .NET 3.5 feature, where the compiler automatically detects the type which an object belongs to. Anonymous types are really important in LINQ query expressions. Now, let’s see a pair of code snippets. Consider the following snippet:

'Anonymous type
Dim firstAnonymous = New With {.Name = "Alessandro", .Age = 30}

This instantiates a firstAnonymous object which is an anonymous type. As you can see, after the New keyword, no type is specified, but the object is initialized and populated with two members, which are respectively a String and an Integer (here, we have used again the Object Initialization Expression technique). These members are considered like normal properties, and every anonymous type must contain at least one. Moreover, anonymous types can contain read-only properties. To accomplish this, you must mark each property with the Key keyword, as you can see in the following code snippet:

'Anonymous type with two readonly properties
Dim secondAnonymous = New With {Key .Name = "Alessandro", Key .Age = 30}

It’s really important to consider that anonymous types are only visible from within the members that define them. This should not be a big problem since, as we said before, anonymous types’ main usage is within LINQ query expressions and not at the class or module level.

Points of Interest

Those we just saw are two really important language features in VB 9.0. You should take a deeper look if you plan to seriously use LINQ for data queries.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Alessandro Del Sole


Member
I'm a Microsoft Visual Basic MVP. I'm an Italian .NET developer and I write articles and books about Visual Basic 2005/2008, WPF and VSTO.

Check out my blog at: http://community.visual-basic.it/AlessandroEnglish
Occupation: Other
Location: Italy Italy

Other popular VB.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
GeneralBindingsource with anonyous Types PinmemberZero-G.3:54 29 Jan '09  
GeneralRe: Bindingsource with anonyous Types PinmemberAlessandro Del Sole7:23 29 Jan '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 Mar 2008
Editor: Smitha Vijayan
Copyright 2008 by Alessandro Del Sole
Everything else Copyright © CodeProject, 1999-2009
Web09 | Advertise on the Code Project