Activator.CreateInstance with type name as string and including parameters
Posted
by Kelly
on Stack Overflow
See other posts from Stack Overflow
or by Kelly
Published on 2010-05-12T16:30:59Z
Indexed on
2010/05/12
16:34 UTC
Read the original article
Hit count: 258
c#3.0
I am working in .Net 3.5, looking at all the various constructors for Activator.CreateInstance. I want to create an instance of a class, calling a particular constructor. I do not have the class type, only its name. I have the following, which works, but actually winds up calling the parameterless constructor first, then the one I want. This is not a terribly big deal, but the parameterless constructor calls a rather busy base constructor, and the constructor I want to call does, too.
In other words, given a type, calling CreateInstance with parameters is easy (only the last two lines below), but given only a type name, is there a better way than this?
ObjectHandle oh = Activator.CreateInstance( "MyDllName", "MyNS." + "MyClassName" );
object o = oh.Unwrap( );
object newObj = Activator.CreateInstance( o.GetType( ), new object[] { param1 } );
return ( IMyDesiredObject )newObject;
Thanks!
© Stack Overflow or respective owner