Del via


Creating a class that has an anonymous type as a field

Here's another way to use the generic parameter trick to get an anonymous type as a field. The other day, I was trying to store the result of a lambda expression in a field, but the lambda was typed as Func(Of <anonymoustype>) and since there is no type inference for fields, and I didn't want to use object (which would be perfectly fine normally, but in this case I wanted a typed anonymous type), I used a similar trick to a post I did a while ago on creating collections of anonymous types.

However, this is not as straightforward because we cannot rely on type inference in the constructor. What I would have liked to be able to do is something like this:

 Public Class Test(Of T)
    Private x As Func(Of T)
    Sub New(y As T)
    End Sub
End Class

Sub UseTest()
    Dim x = new Test(New With {.x = 10, .y = "Tim"})
End Sub

However, this doesn't quite work because we currently don't allow type inference on constructor calls; that is, you have to explicitly state the type parameter for T when you new an object.

Ok, so let's try another technique, which involves using a factory method:

 Public Class TestFactory
    Public Shared Function CreateTest(Of T)(x As T) As Test(Of T)
        Return New Test(Of T)
    End Function
End Class

Public Class Test(Of T)
    Private x As Func(Of T)
End Class

Sub UseTest()
    Dim x = TestFactory.CreateTest(New With {.x = 10, .y = "Tim"})
End Sub

Ok, this works now, and you get a Test(Of <anonymoustype>) which has a field that's Func(Of <anonymoustype>), but we had to jump through hoops and use some unnatural techniques to get this.

In fact, since the main benefit of anonymous types is to avoid creating types, but in this case we have to create a factory class in order to get to this "hack", we didn't really gain anything.

This definitely belongs to the category "interesting, but I would never use this unless I wanted to confuse people". But it really shows how powerful type inference is for generic parameters.

However, I'm sure someone will find a use for this.

Anyways, I'll try to stop beating this horse :)

 

Technorati Tags: VisualBasic, VB9, AnonymousTypes

Comments