This discussion is building upon a previous post on how to acquire an anonymous type ... type.
The next question is, how can you cast an arbitrary object into an anonymous type? At a glance this doesn't seem possible as you cannot directly express the type of an anonymous type in code. For instance the following code is not legal.
Dim o As Object = SomeCall() Dim x = Directcast(o, New With {.a = 5})
Even though it's not possible to directly express the type in code, we can indirectly express it via type inference. Anonymous Types are strongly typed in the compiler and it is possible to infer these types where inference is available.
Public Function CastSpecial(Of T)(ByVal o As Object, ByVal t As T) As T Return DirectCast(o, T) End Function
The above function allows us to perform a DirectCast as long as we have an instance of the type we want to cast to. Now we can call the code and passing in the appropriate anonymous type instance.
Dim o As Object = SomeCall() Dim x = CastSpecial(o, New With {.a = 5})
There are a couple of caveats to this approach though.