How to load a type from type name and assembly name

I need to get an instance of a type whose name and name I will have at runtime. I know in advance that the type will have a constructor without parameters. What is the easiest way to do this?

This waaaaaaay is harder than I hoped it would be.

Edit: I do not, if relevant, but the assembly will be referenced. I do not need to load it from a disk or something like that.

+6
source share
7 answers

From MSDN :

Method Activator.CreateInstance (String, String)

Creates an instance of the type whose name is specified using the named collection and default constructor.

 public static ObjectHandle CreateInstance( string assemblyName, string typeName ) 

Example:

 var assemblyName = "System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; var typeName = "System.Net.WebClient"; var instance = Activator.CreateInstance(assemblyName, typeName).Unwrap(); 
+5
source

If the reference to System.Web.dll is not a problem for you, there is a little-known method BuildManager.GetType that is quite effective. It does not even require an assembly name, since it scans types in assemblies in the current AppDomain execution path.

Thus, the code will look like this:

 object instance = Activator.CreateInstance(BuildManager.GetType("MyNamespace.MyClass", true)); 
+3
source

The following is enough:

 var assmebly = Assembly.Load("FullyQualifiedAssemblyName"); var type = assmebly.GetType("FullTypeName"); var instance = Activator.CreateInstance(type); 
+2
source
 Type referencedType = typeof(AReferencedType); AReferencedType instance = Activator.CreateInstance<AReferencedType>(); or Type type = Type.GetType("Type full name"); object instance = Activator.CreateInstance(type); 
+2
source
 Activator.CreateInstance(Type.GetType("System.Int32")); 

Activator

A type

+2
source

Something works here using the fancy dynamic keyword. You will need to refer to another class to pass the test or use the build event to copy through the built-in DLL.

 namespace TestLibrary { [TestFixture] public class Tests { [Test] public void FileCheck() { dynamic otherClass = AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap("OtherLibrary.dll", "Prefix.OtherLibrary.SomeClass"); otherClass.SayHello(); // look, ma! no casting or interfaces! } } } namespace Prefix.OtherLibrary { public class SomeClass { public void SayHello() { Console.WriteLine("Hello, world."); } } } 

Unlike Activator , AppDomain.CurrentDomain.CreateInstanceFromAndUnwrap accepts the file name as the first argument, not the type specifier. This is sometimes useful, especially when you don't care about a strong build name.

+1
source

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


All Articles