How to: Declare an Instance of an Anonymous Type

Anonymous types enable you to create objects without writing a class definition for the data type. Instead, the compiler creates a class for you. Because the name of the data type is not specified, the type is referred to as an anonymous type.

You declare an instance of an anonymous type by using an initializer list to specify its properties. You provide the name of the instance, the name of each property, and the initial value of each property, and indicate whether each property is a key property.

Declaration

To declare an instance of an anonymous type

  1. Start a Dim statement without an As clause.

    Dim instanceName

  2. In the same statement, assign to instanceName the list of properties for the type, enclosed in braces and preceded by the keywords New With.

    Dim instanceName = New With {<property names and initial values>}

    Start each new property name with a period, and assign it an initial value. If you want the property to be a key property, precede the property name with the keyword Key. (For more information, see Key (Visual Basic).) Separate the properties by using commas. Notice that you cannot specify the data type of a property directly. The type is inferred from the initial value.

    Dim instanceName = New With {Key .Rank = 8, _
                                 Key .Title = "Comptroller", _
                                 .Location = "headquarters"}
    
  3. The declaration is complete. You can access the properties of instanceName as you would for any object, except that the values of key properties cannot be changed.

    instanceName.Location = "conference"
    Console.WriteLine(instanceName.Title)
    ' The following statement does not compile, because Rank is 
    ' a key property and cannot be changed. 
    ' instanceName.Rank = 9
    
  4. For information about other ways to declare anonymous type properties, see How to: Infer Property Names and Types in Anonymous Type Declarations.

Robust Programming

An anonymous type is a good choice if you want to create a temporary object to contain related data, or if you want to have a different selection of properties for each declaration.

There are limitations on the use of anonymous types. Most importantly, the name for the anonymous type is not available and cannot appear where a type name is expected in your code. For more information about how to program with anonymous types, see Anonymous Types.

See Also

Tasks

How to: Infer Property Names and Types in Anonymous Type Declarations

Concepts

Local Type Inference

Anonymous Types

Reference

Key (Visual Basic)