4
votes

I wish to create an instance of a class, using a string value. According to what I read here: Activator.CreateInstance Method (String, String) it should work!

public class Foo
{
    public string prop01 { get; set; }
    public int prop02 { get; set; }
}   

//var assName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
var assName = System.Reflection.Assembly.GetExecutingAssembly().GetName().FullName; 
var foo = Activator.CreateInstance(assName, "Foo");

Why won't this work? I get the following error:

{"Could not load type 'Foo' from assembly 'theassemblyname, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.":"Foo"}

2

2 Answers

4
votes

Instead of the simple type name, you should use the full qualified type name, including the entire namespace.

Like this:

var foo = Activator.CreateInstance(assName, "Bar.Baz.Foo");

As MSDN says:

The fully qualified name of the preferred type.

3
votes

Either use fully qualified name, as proposed already:

var foo = Activator.CreateInstance(assName, "FooNamespace.Foo");

Or get the type by the name:

var type = System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
                                      .First(x=>x.Name=="Foo");
var foo = Activator.CreateInstance(type);

More simple is to use directly your Foo class:

var foo = Activator.CreateInstance(typeof(Foo));