473,786 Members | 2,611 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Instantiating an object dynamically in C#?

Hi,

Does anyone know how/if you can instantiate a C# reference type object dynamically? More specifically, my project has a number of classes that I've created and in some cases it would be very handy to be able to instantiate them based on a string variable representing their class name.

Here's an example of what I'd be looking to do.

public object DynamicInstanti ation(string className)
{
return new [dynamic intantiation sytax here using className varibable value];
}

I rember doing something like this once in a Java class long ago and I figured that since C# has so many similarities that there must be a way but I've not been able to find a working example in any MS documentation.

Any help would be much appreciated!

---
Posted using Wimdows.net NntpNews Component -

Post Made from http://www.DotNetJunkies.com/newsgroups Our newsgroup engine supports Post Alerts, Ratings, and Searching.
Nov 16 '05 #1
4 20303
Absolutely ... what you're looking for is reflection. Using reflection
you can dynamically load a type and execute a method all without the
compiler knowing what type you'll be using at run-time. Here's a great
article that shows just how to do this:
http://www.csharphelp.com/archives/archive200.html

Joel Martinez
http://www.onetug.org - Orlando .NET User Group
http://www.codecube.net - blog

Nov 16 '05 #2
What you may be looking for is Reflection, which is the catch-all name
for a set of classes and methods in C# that allow you to examine the
class hierarchy and get information about methods, properties, and
other things. Take a look at documentation for: Type, MethodInfo,
PropertyInfo, ConstructorInfo , among others.

However, it sounds to me as though what you want to produce is a
Factory. Do some research on the Factory Method and Abstract Factory
design patterns, made famous by Gamma, Helm Johnson, and Vlissides in
their book "Design Patterns". (There are also plenty of on-line
references, including ones that give code examples in C#.)

Nov 16 '05 #3
You can dynamically load a plug in that implements an interface without
knowing the name of the class.
http://www.geocities.com/jeff_louie/OOP/oop13.htm

You can dynamically instantiate an instance of a class that is loaded in
an assembly if you know the fully qualified class name. Here is a few
snippets of code that I wrote today.

namespace TestClassFactor y
{
interface IDrawable
{
void DrawYourself();
}
interface IConstructDrawa ble
{
string Name();
IDrawable Instantiate();
}
class DrawableConstru ctor : IConstructDrawa ble
{
private Type t;
private string name="Drawable" ;
public string Name()
{
return name;
}
public DrawableConstru ctor(Type t, string name)
{
this.t= t;
this.name= name;
}
public IDrawable Instantiate()
{
if (typeof(IDrawab le).IsAssignabl eFrom(t)) // safer
{
// dynamically load this class
return (IDrawable)Acti vator.CreateIns tance(t);
}
else return null;
}
}
Main stuff...
Module[] moduleArray;
moduleArray = Assembly.GetExe cutingAssembly( ).GetModules(fa lse);
//In a simple project with only one module, the module at index
// 0 will be the module containing this class.
Module myModule = moduleArray[0];
Type myType;
myType = myModule.GetTyp e("TestClassFac tory.Triangle", false, false);
factory.Add(new DrawableConstru ctor(myType,myT ype.Name));
}
Regards,
Jeff
Does anyone know how/if you can instantiate a C# reference type object

dynamically? More specifically, my project has a number of classes that
I've created and in some cases it would be very handy to be able to
instantiate them based on a string variable representing their class
name.<

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Nov 16 '05 #4
DotNetJunkies User napisa³(a):
Here's an example of what I'd be looking to do.

public object DynamicInstanti ation(string className)
{
return new [dynamic intantiation sytax here using className varibable value];
}

Any help would be much appreciated!


I am surprise that System.Activato r class wasn't mentioned yet. It can
do exactly what you want:

using System;

public class A
{

}

public class B
{

}

public class App
{
public static void Main()
{
object a = Activator.Creat eInstance(null, "A").Unwrap ();
object b = Activator.Creat eInstance(null, "B").Unwrap ();

Console.WriteLi ne(a is A);
Console.WriteLi ne(b is B);
}
}

Regards,
Marcin
Nov 16 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2274
by: FredC | last post by:
S Name Microsoft Windows XP Professional Version 5.1.2600 Service Pack 2 Build 2600 Total Physical Memory 1,024.00 MB MDE 2003 Version 7.1.3008 ..NET Framework 1.1 Version 1.1.4322 SP1 Microsoft Visual C# .NET 69462-335-0000007-18707 Crystal Reports for Visual Studio .NET AAP50-GS0000S-WCK00C3 The code below shows the instantiation of multiple V47 objects. These
1
1022
by: Reza Nabi | last post by:
Bakground: I have a webform (LoadCtl.aspx) which loads the user control to a placeholder dynamically based on the ctlName querystring passed in the URL. Webform (LoadCtl.aspx) also passes a variable (targetId) in to the usercontrol (IntergySite.aspx) by calling its setter method. Currently, I am using if-then-else and hardcoded the User Control Object to do casting and call the setter method. Question: Is there any way I could load,...
3
1855
by: Andy Fish | last post by:
Hi, Say I had a repeater-like situation but were I wanted to have every 3rd item look different instead of every alternating one. I could write my own custom control and in the ASPX file something like this: <myControl> <mainItemTemplate>...</> <secondItemTemplate>...</> <thirdItemTemplate>...</>
6
1627
by: Gary Frank | last post by:
What are the ramifications if I were to instantiate an object tens of thousands of times and add them to an array? Or hundreds of thousands of times? Do you know if the act of instantiating a class takes a lot of storage or other resources? Would it be a severe performance penalty? From the .Net help doc:
1
2207
by: Marja Ribbers-de Vroed | last post by:
I've been provided with a custom ActiveX DLL (written in C++) that reads a certiifcate to generate a signature for a passed XML string, and I'm having trouble instantiating it. The DLL is registered succesfully on my computer and I've explicitly granted IUSR_<machinename> to use it. The DLL comes with a testtool (written in Visual Basic) which instantiates the object like this: Dim loCertCryptCOM As New CCOMCRYPTLib.CCrypt As you can...
3
4945
by: Nagesh | last post by:
hi, I have seen the winvnc(tightvnc server) source code in this I seen that class member funtions are calling without instantiating the object i.e. like vncService::ShowDefaultProperties() where vncService is a class name not an refrence or instantiated object. is the above notation is possible or not?if yes how should i declare that class(vncService) so that i can call without instantiating the object. If any of u know pls answer to...
23
1945
by: digitalorganics | last post by:
How can an object replace itself using its own method? See the following code: class Mixin: def mixin(object, *classes): NewClass = type('Mixin', (object.__class__,) + classes, {}) newobj = NewClass() newobj.__dict__.update(object.__dict__) return newobj
3
1667
by: Randy | last post by:
Hi, I was learning about RTTI when I ran across this example. This line, out of the example, confused me. It is declaring a pointer to a base type and instantiating it with a derived class. I can say the words ... yet I don't get it. What do I have, a base or a derived? Can anyone push me in the right direction. abc *abc_pointer = new xyz();
7
6223
by: john_smith_1221 | last post by:
Hello, I need to use the rand() function to generate a random value, I already know how to do it with srand(time(NULL)) and its "randomness" is sufficient for me, the problem is my code requires to have that in a struct constructor, which means that rand() will be called upon object instantiation, my code creates objects dynamically all at once, and that results in the SAME VALUE for that class member for each object, that obviously is...
0
9497
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10164
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9962
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7515
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6748
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.