Someone on Stack Overflow today asked how to dynamically instantiate a type that doesn't have a default constructor on the .NET Compact Framework. As an example, let's say you have a type called "Foo" which takes some parameters in its constructor:

public class Foo
{
    public Foo(string s, int i)
    {
        // do stuff with s, i
    }
}

So now with no information other than the name of the type as a string ("Application1.Foo" in this case), you want to spin up an instance of that type.

On the full framework you'd use an overload of Activator.CreateInstance, like this:

string s = "Application1.Foo";
Type t = Assembly.GetExecutingAssembly().GetType(s);
Foo f = Activator.CreateInstance(t, "hello", 17) as Foo;

But on the Compact Framework, the overload for CreateInstance that lets you pass extra parameters doesn't exist. Instead, you have to use the GetConstructor method to determine the correct constructor to use. Here's an extension method for the Assembly type to make it easy!

public static class AssemblyExtensions { static object CreateInstance(this 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); } }

Note the use of LINQ's "Select" method to turn the parameters into an array of types! Pretty funky! Now you can just type this, even on the Compact Framework:

Foo f = Assembly.GetExecutingAssembly()

.CreateInstance("SmartDeviceProject1.Foo", "hello", 17) as Foo;