?
Solved

Instantiating class at run time

Posted on 2003-03-20
8
Medium Priority
?
344 Views
Last Modified: 2010-04-15
Is it possible to instantiate a class whose name I'll know only at run time? For example, I have a list of classes, either in a configuration file or in a database that lists classes all derived from an interface. How can I instantiate these at run time, similar to what Java does with the JDBC Class.forName method.

Thanks!
0
Comment
Question by:athomas4219
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 18

Expert Comment

by:testn
ID: 8178782
You can see sample code from
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemActivatorClassCreateInstanceTopic.asp

Basically, you'll need to import System.Reflection and then call Activator.CreateInstance("assembly.dll",
"namespace.namespace2.classname", true, BindingFlags.Instance|BindingFlags.Public, null, args, null, activationAttributes, null), it will return an object. Then you can cast it to the object that you want.

however, this is a bit unlike Class.forName.  Activator.CreateInstance will create an object directly which is what you want :D
0
 

Expert Comment

by:Shiva217
ID: 8181155
there is another way of doing this..

Assembly.CreateInstance();

e.g.

object myInstance = myAssembly.CreateInstance("MyNamespace.MyClass");



To get an instance of an Assembly object you can do:

Assembly myAssembly = Assembly.LoadFrom("assemblyPathname.dll");



Once you have your instance of your object you can manipulate it, ie call methods on it:


MethodInfo myMethodInfo = myInstance.GetType().GetMethod("MethodIWantToExecute");
object resultOfMethod = myMethodInfo.Invoke(myInstance, new object[] {"a string parameter", 12, true});

the object[] is the parameters passed into the method. To find these out at runtime, you can use:

myMethodInfo.GetParameters() // this returns a ParameterInfo[]

Hope this helps.
0
 

Author Comment

by:athomas4219
ID: 8567458
I tried the following code and received an error, which also follows:

Code:

                  object session = null;
                  object[] sessionArgs = { "username", "password", "repository" };

                  try
                  {
                        session = Activator.CreateInstance( @"C:\Source\Radix\Base\bin\Release\Base.dll", "Iminformation.Radix.Base.RdxSession", true, BindingFlags.Instance | BindingFlags.Public, null, sessionArgs, null, null, null );
                        Console.WriteLine( "Session has been created." );
                  }
                  catch( Exception e )
                  {
                        Console.WriteLine( "Error creating instance:\n\t{0}", e.Message );
                        return;
                  }

Error:

File or assembly name C:\Source\Radix\Base\bin\Release\Base.dll, or one of its dependencies, was not found.

Any thoughts?
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Expert Comment

by:Shiva217
ID: 8583568
Yes,

the problem is, base.dll references something (ie another dll) that the program you're writing doesnt reference... hmm, let me try and explain AppDomains.

Each program is contained within its own application domain (the class representing this is AppDomain), all assemblies (ie dll's exe's) that are needed such as System.dll are loaded into your AppDomain, now, the dll Base.dll is referencing a dll that isnt in your application.

I know how to load up the assemblies required, but I only know how to do this is you were using the technique i listed above... let me know if you are,  then I'll post the method.

(also, there is one other possibility, you have the dll file path wrong.. but i assume that is not the case)
0
 

Author Comment

by:athomas4219
ID: 8592115
I wonder if maybe a little explanation is in order. What I'm trying to do is this: I am writing an application that has a navigation bar. Parts of this navigation bar (a TreeView) or rendered differently based on the functionality, or module, as I call it, in each position. For example, I have an Inbox and a Search module. My goal is to be able to write an interface, IModule, that will allow each of these to be rendered differently, depending on the reqruirements of the module. I want to allow the user/developer to write his own assembly, inherit from IModule, and put a line in a database table. I then want the rendering code to instantiate the user/developer's class and use the IModule interface to render the TreeView. As such, I need to be able to instantiate a class at run-time and call methods on it.

What's the best way to do this?

Thanks!
0
 

Author Comment

by:athomas4219
ID: 8600925
Here's what I ended up doing:

Assembly moduleAssembly = Assembly.LoadFrom( "AssemblyName.dll" );
Type moduleType     = moduleAssembly.GetType( "My.Namespace.Class.Name" );

myInterfaceObject = (IMyInterface)Activator.CreateInstance( moduleType, null );

// Call a method on my newly created object
moduleImpl.Render( "argument1", "argument2" );

This was what I'd wanted and, after research, it turned out to be as easy as I'd hoped and expected.

Thanks!
0
 

Accepted Solution

by:
modulo earned 0 total points
ID: 11805723
PAQed, with points refunded (35)

modulo
Community Support Moderator
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
In this video we outline the Physical Segments view of NetCrunch network monitor. By following this brief how-to video, you will be able to learn how NetCrunch visualizes your network, how granular is the information collected, as well as where to f…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…

764 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question