Paul Grimshaw
Paul Grimshaw

Reputation: 21044

IEnumerable property creation in Reflection.Emit

I am trying to create a property of type IEnumerable<AnotherDynamicType> using Reflection.Emit.

I have a helper method that adds properties fine, accepting a Type as input:

public void AddProperty(TypeBuilder typeBuilder, string propertyName, Type type) 
{
    ....
}

This can be called in this manner:

AddProperty(typeBuilder,"MyPropertyName",typeof(string));

However now I wish to add a property to the class:

public IEnumerable<AnotherDynamicType> MyList {get;set;}

How do I define the "Type" of this property for the call, given that the target AnotherDynamicType is also dynamically created?

The following doesn't compile:

AddProperty(typeBuilder,"MyPropertyName",typeof(IEnumerable<typeof(anotherDynamicType)>));

Upvotes: 2

Views: 143

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149636

You can use Type.MakeGenericType:

var anotherTypeEnumerable = typeof(IEnumerable<>)
                            .MakeGenericType(anotherDynamicType);

Upvotes: 3

Related Questions