<p>I'm using the .NET CF 3.5. The type I want to create does not have a default constructor so I want to pass a string to an overloaded constructor. How do I do this?</p>

<p>Code:</p>

<pre><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
</code></pre>

[{'answer_id': 29444, 'author': 'Matt Hamilton', 'author_id': 615, 'author_profile': 'https://Stackoverflow.com/users/615', 'pm_score': 0, 'selected': False, 'text': '<p>See if this works for you (untested):</p>\n\n<pre><code>Type t = a.GetType("type info here");\nvar ctors = t.GetConstructors();\nstring s = "Pass me to the ctor of t";\nMyObj o = ctors[0].Invoke(new[] { s }) as MyObj;\n</code></pre>\n\n<p>If the type has more than one constructor then you may have to do some fancy footwork to find the one that accepts your string parameter.</p>\n\n<p>Edit: Just tested the code, and it works.</p>\n\n<p>Edit2: <a href="https://stackoverflow.com/questions/29436/compact-framework-how-do-i-dynamically-create-type-with-no-default-constructor#29472">Chris\' answer</a> shows the fancy footwork I was talking about! ;-)</p>\n'}, {'answer_id': 29472, 'author': 'Chris Karcher', 'author_id': 2773, 'author_profile': 'https://Stackoverflow.com/users/2773', 'pm_score': 4, 'selected': True, 'text': '<pre><code>MyObj o = null;\nAssembly a = Assembly.LoadFrom("my.dll");\nType t = a.GetType("type info here");\n\nConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(string) });\nif(ctor != null)\n   o = ctor.Invoke(new object[] { s });\n</code></pre>\n'}, {'answer_id': 29481, 'author': 'Matt Hamilton', 'author_id': 615, 'author_profile': 'https://Stackoverflow.com/users/615', 'pm_score': 1, 'selected': False, 'text': '<p>Ok, here\'s a funky helper method to give you a flexible way to activate a type given an array of parameters:</p>\n\n<pre><code>static object GetInstanceFromParameters(Assembly a, string typeName, params object[] pars) \n{\n    var t = a.GetType(typeName);\n\n    var c = t.GetConstructor(pars.Select(p =&gt; p.GetType()).ToArray());\n    if (c == null) return null;\n\n    return c.Invoke(pars);\n}\n</code></pre>\n\n<p>And you call it like this:</p>\n\n<pre><code>Foo f = GetInstanceFromParameters(a, "SmartDeviceProject1.Foo", "hello", 17) as Foo;\n</code></pre>\n\n<p>So you pass the assembly and the name of the type as the first two parameters, and then all the constructor\'s parameters in order.</p>\n'}]
['https://Stackoverflow.com/questions/29436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/636/']