Reputation: 361
This should be simple but I can't find anywhere that tells me how to do this. I've got a class, it's in the same dll as the one I am using to do this.
All I want to do is something like.
thing.InstanceClass("ClassName");
I would like to do this without doing:
Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");
And that is because the classes I would like to instance using reflection are in the same assembly.
Upvotes: 0
Views: 273
Reputation: 104692
If it's a known (referenced, not COM etc.) type within your project, then the best way is to use the strongly-typed CreateInstance
function:
MyClass instance = Activator.CreateInstance<MyClass>();
This will save much of performance cost since there is no boxing/unboxing.
Upvotes: 0
Reputation: 58703
I believe System.Activator.CreateInstance is the framework method you seek.
Upvotes: 0
Reputation: 61589
Type instanceType = Type.GetType("SomeNamespace.SomeType");
object instance = Activator.CreateInstance(instanceType);
You can resolve it through Type.GetType(...)
if the assembly is already loaded into the AppDomain.
If you need the assembly you can use Assembly.GetEntryAssembly
, or possibly typeof(SomeType).Assembly
where SomeType
is in your target assembly.
Upvotes: 5