views:

49

answers:

2

hey all, I need to call the Non default constructor when using assembly.CreateInstance. how?

A: 

Try this overload:

public Object CreateInstance (
    string typeName,
    bool ignoreCase,
    BindingFlags bindingAttr,
    Binder binder,
    Object[] args,
    CultureInfo culture,
    Object[] activationAttributes
)

It has an args paramter.

C. Dragon 76
What's the last parameter about? activationAttributes??
Shaza
The last parameter is only useful for remoting scenarios. For example, you can specify a UrlAttribute (http://msdn.microsoft.com/en-us/library/system.runtime.remoting.activation.urlattribute.aspx).
C. Dragon 76
+3  A: 

Activator.CreateInstance is a much friendlier API than Assembly.CreateInstance to use for these kinds of things:

var type = Type.GetType("MyNamespace.MyClass, MyAssembly");
Activator.CreateInstance(type, constructorParam1, constructorParam2);
Igor Zevaka
You need to wrap the params into an Object[]. `Activator.CreateInstance(type, new [] { constructorParam1, constructorParam2 });`
Mark H
@Mark, no you don't. It's a varargs method.
Matthew Flaschen
@Mark H - http://msdn.microsoft.com/en-us/library/w5zay9db(VS.71).aspx - `Function(params object[])` is a function taking 0 or more arguments.
Igor Zevaka
@Matthew - it is a `params` methood; `varargs` is subtly different - you *can* use `varargs` from C# - but it is an undocumented keyword / compiler feature.
Marc Gravell
@Marc Gravell huh, didn't even know about those ones. For more info see this link: http://www.eggheadcafe.com/articles/20030114.asp That's just so weird looking, very much like C vararg macros.
Igor Zevaka
Oops, my mistake on the params arg. I've used CreateInstance many times and always wrapped the args in an object []. (It probably didn't show up in my intellisense the first time I use it.). It works the way I've been doing it, so I've always assumed it's been correct - didn't realise I was doing it the hard way.
Mark H