Visual Basic .NET Language Object Initializers


Example

  • Named Types

     Dim someInstance As New SomeClass(argument) With {
         .Member1 = value1,
         .Member2 = value2
         '...
     }
    

    Is equivalent to

     Dim someInstance As New SomeClass(argument)
     someInstance.Member1 = value1
     someInstance.Member2 = value2
     '...
    
  • Anonymous Types (Option Infer must be On)

      Dim anonymousInstance = New With {
          .Member1 = value1,
          .Member2 = value2
          '...
      }
    

    Although similar anonymousInstance doesn't have same type as someInstance

    Member name must be unique in the anonymous type, and can be taken from a variable or another object member name

      Dim anonymousInstance = New With {
          value1,
          value2,
          foo.value3
          '...
      }
      ' usage : anonymousInstance.value1 or anonymousInstance.value3
    

    Each member can be preceded by the Key keyword. Those members will be ReadOnly properties, those without will be read/write properties

      Dim anonymousInstance = New With {
          Key value1,
          .Member2 = value2,
          Key .Member3 = value3
          '...
      }
    

    Two anonymous instance defined with the same members (name, type, presence of Key and order) will have the same anonymous type.

      Dim anon1 = New With { Key .Value = 10 }
      Dim anon2 = New With { Key .Value = 20 }
    
      anon1.GetType Is anon2.GetType ' True
    

    Anonymous types are structurally equatable. Two instance of the same anonymous types having at least one Key property with the same Key values will be equal. You have to use Equals method to test it, using = won't compile and Is will compare the object reference.

      Dim anon1 = New With { Key .Name = "Foo", Key .Age = 10, .Salary = 0 }
      Dim anon2 = New With { Key .Name = "Bar", Key .Age = 20, .Salary = 0 }
      Dim anon3 = New With { Key .Name = "Foo", Key .Age = 10, .Salary = 10000 }
    
      anon1.Equals(anon2) ' False
      anon1.Equals(anon3) ' True although non-Key Salary isn't the same
    

Both Named and Anonymous types initializer can be nested and mixed

    Dim anonymousInstance = New With {
        value,
        Key .someInstance = New SomeClass(argument) With {
            .Member1 = value1,
            .Member2 = value2
            '...
        }
        '...
    }