Compact Framework - how do I dynamically create a type without a default constructor?

I am using .NET CF 3.5. The type I want to create does not have a default constructor, so I want to pass the string to the overloaded constructor. How to do it?

the code:

Assembly a = Assembly.LoadFrom("my.dll"); Type t = a.GetType("type info here"); // All ok so far, assembly loads and I can get my type string s = "Pass me to the constructor of Type t"; MyObj o = Activator.CreateInstance(t); // throws MissMethodException 
+6
reflection c # compact-framework
source share
4 answers
 MyObj o = null; Assembly a = Assembly.LoadFrom("my.dll"); Type t = a.GetType("type info here"); ConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(string) }); if(ctor != null) o = ctor.Invoke(new object[] { s }); 
+9
source share

@Jonathan Because the Compact Framework should be as thin as possible. If there is another way to do something (for example, the code I posted), they usually do not duplicate functionality.

Rory Blyth once described the Compact Framework as "a wrapper around System.NotImplementedExcetion." :)

+4
source share

Ok, here is a funky helper method to give you a flexible way to activate a type with a given array of parameters:

 static object GetInstanceFromParameters(Assembly a, string typeName, params object[] pars) { var t = a.GetType(typeName); var c = t.GetConstructor(pars.Select(p => p.GetType()).ToArray()); if (c == null) return null; return c.Invoke(pars); } 

And you call it like this:

 Foo f = GetInstanceFromParameters(a, "SmartDeviceProject1.Foo", "hello", 17) as Foo; 

So, you pass the assembly and the type name as the first two parameters, and then all the constructor parameters are fine.

+1
source share

See if this works for you (untested):

 Type t = a.GetType("type info here"); var ctors = t.GetConstructors(); string s = "Pass me to the ctor of t"; MyObj o = ctors[0].Invoke(new[] { s }) as MyObj; 

If a type has more than one constructor, you may need to do some fancy work to find one that takes your string parameter.

Edit: just checked the code and it works.

Edit2: Chris's answer shows the fashion legs that I talked about !; -)

0
source share

All Articles