Tuesday, October 17, 2006

Object Instantiation with Reflection


So i need to instantiate objects at runtime. Whats the best way of doing this? Reflection !

What you need to do is obtain the Type object representing the type of object you want to instantiate then call the Type.GetConstructor method. This will give you the System.Reflection.ConstructorInfo that represents the constructor you want to use. Then execute the ConstructorInfo.Invoke method.


Code : sample

----Type type = typeof(StringBuilder);
----Type[] argTypes = new Type[] {typeof(System.String), typeof(System.Int32);}

----ConstructorInfo cInfo = type.GetConstructor(argTypes);

----object[] argVals = new object[] {"something", 30};
----StringBuilder sb = (StringBuilder) cInfo.Invoke(argVals);

No comments: