Passing list of objects to create with arguments to constructor or method

Basically what I'm trying to do is to make a class that can mass-create objects using

Activator.CreateInstance(Type type, params object[] args)

I will need to pass all the object blueprints to a constructor of a class called ObjectMap. It will need to be pairs of a type and the arguments. It can also be a method in another class instead of a constructor if that allows for a solution.

sort of like

new ObjectMap([Type, somevalue, somevalue, somevalue], [Type, somevalue], [Type] ...)

or

Resources.AddObjectMap([Type, somevalue, somevalue, somevalue], [Type, somevalue], [Type] ...)

I have no idea how to make it so that you can pass a variable amount of pairs with a variable amount of arguments (even 0). Heck I'm even having a hard time trying to explain the issue. Ask me anything that's unclear to you =S

Gr.Viller

Jon Skeet
people
quotationmark

I would suggest you encapsulate the "type and args" into a specific type... then you can use a params array of that. For example:

// TODO: Find a better name :)
public class TypeBlueprint
{
    public Type Type { get; set; }
    public List<object> Arguments { get; set; }

    public TypeBlueprint()
    {
        this.Arguments = new List<object>();
    }

    public TypeBlueprint(Type type, params object[] arguments)
    {
        this.Type = type;
        this.Arguments = arguments.ToList();
    }
}

Then:

public ObjectMap(params TypeBlueprint[] blueprints)

And call it with:

var map = new ObjectMap(new TypeBlueprint(typeof(Foo), "x", "y", "z"),
                        new TypeBlueprint { Type = typeof(Bar),
                                            Arguments = { 1, 2, 3 } });

That demonstrates using both constructor parameters and object initializers to specify the type and arguments. Use whichever is best for you.

people

See more on this question at Stackoverflow