You should cast to Form2
, not to Form
.
I don't know where is problem (if you cast to correct type), but if you have corresponding constructor, your code works fine for me.
You can try to pass arguments as object[]
(object
array) - CreateInstance(Type type, object[] args), but also you can pass arguments by the way you pass them (because method accepts params object[] args
).
Try to replace this line:
var obj = (Form)Activator.CreateInstance(Type.GetType("myproject.Form2"),1,"test");
by this:
var obj =
(Form2)Activator.CreateInstance(Type.GetType("myproject.Form2"), new object[] {1, "test"});
Also, you can use typeof
to get Type
instance:
var obj = (Form2)Activator.CreateInstance(typeof(Form2), new object[] {1, "test"});
But if you know which type of instance to create at compile time, you should simply create your object using new
:
var obj = new Form2(1, "test");