views:

132

answers:

2

I'm using GetParameter to determine what parameters the constructor needs. I can get a list of them. Now I want to invoke the ctor. Is this possible if there is no empty one?

+1  A: 

Is this what you are looking for? This creates an instance of SqlConnection passing a string to the constructor. If you want to pass more values, simply add them to the array.

        SqlConnection conn;
        conn = (SqlConnection)System.Activator.CreateInstance(typeof(SqlConnection), new object[] { "Server=myserver" });
        Console.WriteLine(conn.ConnectionString);
Bomlin
yes! but my parameters need to be more dynamic than that. I need to look at the constructor and if it has parameters i need to look at each parameter and get at its system type, like boolean or int, and then build an array of those params, setting their value, then passing that to the create instance or ctor.invoke...ParameterInfo[] pi = t.GetConstructors()[0].GetParameters();foreach(ParameterInfo p in pi){ if(p is boolean) { args[idx] = new Boolean(true); } }I don't know. Something like this. I'm not sure what's possible.}
towps
Type realType = Type.GetType(paramInfo.ParameterType.FullName); might do the trick.
towps
Forget this. Although there is probably some convoluted way to do this, I'm going to make sure each of the types declared in my assembly have a default empty constructor so I don't have to worry about the params when getting the object. Then it should be just a matter of going through the properties and setting the values on them... hopefully that's easier. Any comments? Anyone? If it's just as hard, SO will definitely see another question from me!
towps
+3  A: 

Which language? For c# you could use

Activator.CreateInstance(typeof(X), constructorparm1, constructorparam2...)
saret
so what do i get back? a generic object? that i can cast to the type I'm dealing with?
towps
You get back an Object. You'd have to cast it or use the AS operator to get the object as the type you want:X instance = (X)Activator.CreateInstance(typeof(X), constructorparm1, constructorparam2...)
saret
I think the question I need to be asking then is how do I create a system type from a ParameterInfo?I get a list of params for my ctor. I get back paramInfo that tells me the first 2 are bools and the second 2 are ints. Now I need to create an array that hold 2 bools, set to either true or flase of course (based on user input from UI or whatever), and 2 ints set to user input from UI or what have you...
towps
maybe that's a whole new question altogether. but i need something like if(paramInfo is boolean) { args[idx] = new Boolean(txtBool.Value) } if you catch my drift... i realize Boolean constructor takes 0 args but I think I need this kind of flexibility if you will...
towps