Reputation: 16120
I need to get an instance of a type whose name and assembly name I will have at runtime. I know in advance the type will have a parameterless constructor. What's the easiest way to do this?
It's waaaaaaay harder than I was hoping it would be.
Edit: I'm not if this is relevant, but the assembly will be referenced. I don't need to load it from disk or something.
Upvotes: 6
Views: 9015
Reputation: 25200
Here's something that works using the fancy dynamic
keyword. You'll need to reference the other class for the test to pass, or use a build event to copy over the built 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
takes a filename as the first argument rather than a type specifier. This is sometimes useful, especially when you don't care about the strong name of the assembly.
Upvotes: 1
Reputation: 217313
From MSDN:
Activator.CreateInstance Method (String, String)
Creates an instance of the type whose name is specified, using the named assembly 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();
Upvotes: 5
Reputation: 138960
If referencing System.Web.dll is not an issue for you, there is the little-known BuildManager.GetType Method which is quite efficient. It does not even requires the assembly name because it scans for types in assemblies in the current AppDomain execution path.
So the code would be:
object instance = Activator.CreateInstance(BuildManager.GetType("MyNamespace.MyClass", true));
Upvotes: 3
Reputation: 38179
Type referencedType = typeof(AReferencedType);
AReferencedType instance = Activator.CreateInstance<AReferencedType>();
or
Type type = Type.GetType("Type's full name");
object instance = Activator.CreateInstance(type);
Upvotes: 2
Reputation: 46008
Type.GetType(string.Concat(typeName, ", ", assemblyName))
http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx
Upvotes: 8
Reputation: 41767
The following should suffice:
var assmebly = Assembly.Load("FullyQualifiedAssemblyName");
var type = assmebly.GetType("FullTypeName");
var instance = Activator.CreateInstance(type);
Upvotes: 2