-4

i read here how to create anonymous types at runtime in c#

AssemblyBuilder dynamicAssembly =
AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("MyDynamicAssembly"),
  AssemblyBuilderAccess.Run);

string propertyName = "prp_1";
//Type propertyType = new Type();

ModuleBuilder dynamicModule = dynamicAssembly.DefineDynamicModule("MyDynamicAssemblyModule");
TypeBuilder dynamicType = dynamicModule.DefineType("MyDynamicType", TypeAttributes.Public);
PropertyBuilder property =
dynamicType.DefineProperty(
                    propertyName, 
                    System.Reflection.PropertyAttributes.None, 
                    propertyType,             // idk what to put here?
                    new[] { propertyType }    // and here ?
                );

//call this first
AddProperty(dynamicType, propertyName, propertyType );

//then we ' ll dynamic type
Type myType = dynamicType.CreateType();

function that is called

public static void AddProperty(TypeBuilder typeBuilder, string propertyName, Type propertyType)

there is propertyType in the code i dont know what to put there. can i make

 type mytype = \\typefree?

thank you.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
bh_earth0
  • 2,537
  • 22
  • 24

1 Answers1

1

EDIT: This Answer was correct for the question but question has since been changed.

I think you are looking for an object type so if the property was a string then you would be using

typeof(string)

in place of propertyType. Ah sorry missing the anonymous bit. You could try using dynamic

typeof(dynamic)

which would have the same effect as

typeof(object)

but dynamic is not typesafe so any properties that don't exist won't be picked up until runtime and both are a bit like saying 'put anything here'. The safest and best thing to do would be to create a class for the anonymous type.

Dhunt
  • 1,584
  • 9
  • 22
  • the 3rd option should work then. but there is no way to define the type of something anonymous as it is anonymous. – Dhunt Nov 19 '15 at 07:47