4

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 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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));

3 Comments

you could accept solution of @Patrick Hofman and give one upvote for mine :)
Note that the second sample is dangerous if you have multiple types with the same name but within another namespace.
The third sample could be simplified as new Foo() since you already know the type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.