Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an instance based on a stringvalue

Tags:

c#

reflection

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"}

like image 476
Tony_KiloPapaMikeGolf Avatar asked Mar 10 '23 06:03

Tony_KiloPapaMikeGolf


1 Answers

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.

like image 81
Patrick Hofman Avatar answered Mar 15 '23 04:03

Patrick Hofman