Dynamic Assemblies - How to add an existing, known Type to the module being built? RRS feed

  • Question

  • Hi

    We have a need to serialize over a network, the results of a LINQ query.

    The LINQ query uses 'var' (typically) so we often get a new Type created for the items in the resulting sequence.

    We want to provide the client with information about this type so that it can use the results in a DataGridView etc.

    We have done this already in a simpler test setup but this was for defined types that  have an existing Assembly (we serialize the assembly and client later loads it etc and this works fine).

    So we simply want to create a dynamic assembly and then just add this single (anonymous) type to the assembly.

    I would have thought this was straightforward but it seems we cannot do this and must add a type by specifying every field, property etc.

    Surely there is a way to do this?

    Am I going to be forced to examine the anonymous Type, and clone every field/property definition from it, adding them individually to the TypeBuilder?

    I am a little surpised that there is no ModuleBuilder.AddExistingType(Type TypeObject); method...

    Any info much appreciated.


    Thursday, December 11, 2008 10:15 AM


  • There's no such thing as an anonymous type in the CLR.  When you use the var keyword, you are asking the compiler to use type inference to calculate the actual type of the Linq expression.  There's nothing anonymous about the type in the generated IL.  When you create a dynamic assembly, you need to do what the compiler does.  Yes, that's not easy by a long shot.
    Hans Passant.
    • Marked as answer by Zhi-Xin Ye Wednesday, December 17, 2008 7:43 AM
    Thursday, December 11, 2008 12:56 PM