Create instance based on string value

I want to instantiate a class using a string value. According to what I'm reading 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 is this not working? I get the following error:

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

+4
source share
2 answers

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

Like this:

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

As MSDN says:

.

+4

, :

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

:

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

Foo:

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

Source: https://habr.com/ru/post/1665323/


All Articles