Metacircular thoughts

June 7, 2008

Imitating Ruby’s anonymous hashes in VB.NET

Filed under: Uncategorized — metacircular @ 10:13 pm

Module Program
    Sub PrintObj(ByVal obj As Object)
        Try
            Console.WriteLine(obj.B)
        Catch ex As MissingMemberException
            ' Do something appropriate here
        End Try
    End Sub

    Sub Main()
        PrintObj(New With {.A = 1, .B = eh})

    End Sub
End Module

Except here we’re passing in an anonymous object where one of the members is XML, something you can’t do in Ruby.

This seems like a reasonable workaround to VB.Net’s infuriating lack of collection initializers if you’re willing to give up type safety, I suppose.

Blog at WordPress.com.