Eugene Goldberg
Eugene Goldberg

Reputation: 15534

how to dynamically instantiate a C# class from assembly, other then running one

I have an assembly (which is other then my running assembly) named "Gcim.Management.Module.dll", from which I need to instantiate a specific class:

Assembly myAssembly = Assembly.LoadFile(@"C:\Projects\Gcim.Management\Gcim.Management.Module\bin\Debug\Gcim.Management.Module.dll");

The class, in which I'm, interested, has a name of "DataSources". I'm trying to iterate over this assembly and match what I'm looking for by name:

var types = myAssembly.ManifestModule.GetTypes();

foreach (var item in types)
{
    if(item.Name == "DataSources")
    {
        Type myType = Type.GetType(item.FullName);

        object targetObject = ObjectSpace.CreateObject(myType);
    }
}

The "ObjectSpace.CreateObject" comes from a third-party library, and for it to work, it needs a valid myType. I am getting a match as I iterate, but myType remains null after Type myType = Type.GetType(item.FullName);

What is the proper way to get the assembly type, so I could instantiate an object of that type?

Upvotes: 0

Views: 111

Answers (1)

Clay
Clay

Reputation: 5084

If item.Name=="DataSources" returns true, then item is the type you want...don't need to call Type.GetType to get it.

However, to answer your question, Type.GetType( string name ) will only return types by full name in the current assembly or the "core" assembly (mscorlib). You can use the assembly qualified name instead...

Type.GetType( item.AssemblyQualifiedName )

It will then find the type.

Upvotes: 2

Related Questions