4

Using a type builder I am OK with creating a type dynamically. Would it be possible to do this from an anonymous type?

I have this so far;

//CreateType generates a type (so that I can set it's properties once instantiated) from an //anonymous object. I am not interested in the initial value of the properties, just the Type.
 Type t = CreateType(new {Name = "Ben", Age = 23});
 var myObject = Activator.CreateInstance(t);

Is it possible to now use Type "t" as a type argument?

My method:

public static void DoSomething<T>() where T : new() 
{
}

I would like to call this method using the dynamically created Type "t". So that I can call;

DoSomething<t>(); //This won't work obviously
1
  • Do you mean you construct an object of an anonymous type and want to get its type in order to create more of them? Commented Mar 8, 2013 at 9:50

1 Answer 1

2

Yes, it is possible. To use the type as a type argument, you need to use the MakeGenericType method:

// Of course you'll use CreateType here but this is what compiles for me :)
var anonymous = new { Value = "blah", Number = 1 };
Type anonType = anonymous.GetType();

// Get generic list type
Type listType = typeof(List<>);
Type[] typeParams = new Type[] { anonType };
Type anonListType = listType.MakeGenericType(typeParams);

// Create the list
IList anonList = (IList)Activator.CreateInstance(anonListType);

// create an instance of the anonymous type and add it
var t = Activator.CreateInstance(anonType, "meh", 2); // arguments depending on the constructor, the default anonymous type constructor just takes all properties in their declaration order
anonList.Add(t);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.