Compartilhar via


Como: Declarar uma instância de um tipo anônimo (Visual Basic)

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 Como: inferir nomes e tipos de propriedade em declarações de tipo anônimo (Visual Basic).

Programação robusta

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 Tipos anônimos (Visual Basic).

Consulte também

Tarefas

Como: inferir nomes e tipos de propriedade em declarações de tipo anônimo (Visual Basic)

Referência

Key (Visual Basic)

Conceitos

Inferência de tipo de variável local (Visual Basic)

Tipos anônimos (Visual Basic)