Search code examples
vb.netanonymous-typesobject-initializers

Is there a way to force the type of a property of a VB.Net anonymous type?


I mean something like this (in bold):

Dim anonType = New With {.Property1 = 10, .Property2 As Decimal? = Nothing}


Solution

  • You could always work around it like this..

    Private Sub test()
        Dim tempDecimal? As Decimal = Nothing
        Dim anonType = New With {.Property1 = 10, .Property2 = tempDecimal}
        ' property value is nothing here, but if tempDecimal isnt declared as nullable,
        'the value will be 0
        anonType.property2 = Nothing 
        anonType.property2 = 5
        'tp will be Decimal here
        Dim tp As Type = anonType.property2.GetType
    End Sub