473,805 Members | 2,191 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dyanamically referring to an object instance

RSH
Hi,

I have a situation where I have multiple objects created from concrete
classes:

// Concrete implementations of the Abstract class ApprovalChain
MarketingApprov alChain MktgAppChain = new MarketingApprov alChain();
AccountingAppro valChain AcctAppChain = new AccountingAppro valChain();

I also have a Department enum
public enum Department
{
Acct,Mktg
}

Armed with that information I need to pass those objects to another class
dynamically. (Im trying to avoid hardcoding the logic is a case conditional:

public class Purchase
{
public Purchase(Approv alChain appChain)
{
...
}

}
back to the original method:
private MarketingApprov alChain MktgAppChain = new MarketingApprov alChain();
private AccountingAppro valChain AcctAppChain = new
AccountingAppro valChain();

public void PurchaseRequisi tion(Department dept)
{
Purchase purchase = new Purchase();<----- is there a way here to use the
string value of the enum to dynamically make reference to the appropriate
ApprovalChain to pass to the Purchase Class Constructor?
}

PsuedoCode: Purchase purchase = new Purchase(dept.T oString() +
"ApprovalChain" );

Thanks alot!

Ron
Nov 30 '07 #1
5 1459
Took me a minute to figure out what you wanted to do.

You're looking for the Activator.Creat eInstance method.

What I would do is:

ApprovalChain appChain;
appChain = (ApprovalChain) Activator.Creat eInstance([fully qualified
name] + dept.ToString() + "ApprovalChain" )
Purchase purchase = new Purchase(appCha in);

I'm not really up on my CreateInstance code but thats definitely what
you're looking for. The string that you pass in has to be the fully
qualified name of the type you are defining.
Nov 30 '07 #2
RSH
Almost....

The only problem is that the objects already have been created and they
contain state that needs to be persisted which is handled by the class that
contains the method Im illustrating here. I need to dynamically construct a
reference to the appropriate object (based on the deparment enum passed to
the method) and then pass the "live" object to the Purchase object. Right
now I am using a case conditionional:

public void PurchaseRequest (int id, double amount, string description,
eGroup group)

{

Purchase purchase;

switch (group)

{

case eGroup.Marketin g:

this.

purchase = new Purchase(id, amount, description, group,
marketingapprov alchain, marketingbudget );

break;

case eGroup.Accounti ng:

purchase = new Purchase(id, amount, description, group,
accountingappro valchain, accountingbudge t);

break;

}

}

}

But since I dont know the number of departments the system will ultimately
contain, I dont want to hardcode the references in a conditional.

Thanks!

Ron

"cfps.Christian " <ge*******@otc. eduwrote in message
news:f6******** *************** ***********@e1g 2000hsh.googleg roups.com...
Took me a minute to figure out what you wanted to do.

You're looking for the Activator.Creat eInstance method.

What I would do is:

ApprovalChain appChain;
appChain = (ApprovalChain) Activator.Creat eInstance([fully qualified
name] + dept.ToString() + "ApprovalChain" )
Purchase purchase = new Purchase(appCha in);

I'm not really up on my CreateInstance code but thats definitely what
you're looking for. The string that you pass in has to be the fully
qualified name of the type you are defining.

Nov 30 '07 #3
>PsuedoCode: Purchase purchase = new Purchase(dept.T oString() +
"ApprovalChain ");

How about a simple mapping table?

Dictionary<Depa rtment, ApprovalChainma p = new Dictionary<Depa rtment,
ApprovalChain>( );
map.Add(Departm ent.Acct, AcctAppChain);
map.Add(Departm ent.Mktg, MktgAppChain);

....

Purchase purchase = new Purchase(map[dept]);
Mattias

--
Mattias Sjögren [C# MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 30 '07 #4
On 2007-11-30 14:03:41 -0800, "RSH" <wa************ *@yahoo.comsaid :
[...]
But since I dont know the number of departments the system will ultimately
contain, I dont want to hardcode the references in a conditional.
It's difficult for me to be sure I completely understand the question.
I don't find the description very organized. But, that said...

It seems to me that what you've got are already-existing instances of
ApprovalChain-derived classes that are somehow related to your
instantiation of the Purchase class. It appears you may also have a
class named "Budget" that also has derived versions you're using.

Given that, you may want to consider just storing those instances in a
Dictionary<T>, so that you can easily look them up according to their
enum value. For example:

enum Department
{
Acct, Mktg
}

struct DepartmentObjec ts
{
public readonly ApprovalChain ApprovalChain;
public readonly Budget Budget;

public DepartmentObjec ts(ApprovalChai n ApprovalChain, Budget Budget)
{
this.ApprovalCh ain = ApprovalChain;
this.Budget = Budget;
}
}

static Dictionary<Depa rtment, DepartmentObjec tsdictDepartmen ts;

// run once somewhere (e.g. static constructor for whatever class
// contains the "dictDepartment s" object)
foreach (Department dept in Department.GetV alues())
{
switch (dept)
{
case Acct:
dictDepartments .Add(dept, new DepartmentObjec ts(new
AccountingAppro valChain(), new AccountingBudge t()));
break;
case Mktg:
dictDepartments .Add(dept, new DepartmentObjec ts(new
MarketingApprov alChain(), new MarketingBudget ()));
break;
}
}
// then wherever you need to match the enum to an instance, something
// like this:

Department dept = // initialized however...;

ApprovalChain approval = dictDepartments[dept].ApprovalChain;

// Or you could do this:
DepartmentObjec t do = dictDepartments[dept];
Purchase purchase = new Purchase(id, amount, description, dept,
do.ApprovalChai n, do.Budget);

etc.

Note that at some point you do need to hardcode the relationship
between your enum and the class each value represents. Depending on
the actual names you've used for things it certainly is possible to use
reflection to even automate that, but it seems to me it wouldn't really
buy you much. It's not like you can just go adding new ApprovalChain
and Budget objects without visiting the code that uses those objects
and verifying you've done everything right anyway (or at least you
ought to be).

Pete

Nov 30 '07 #5
RSH
Peter,

Thanks! Good stuff...that worked perfectly!

I agree that at some point I need to hardcode the names, but I wanted to do
it in one place only. Your solution will provide me that.

thanks!
Ron
"Peter Duniho" <Np*********@Nn OwSlPiAnMk.comw rote in message
news:2007113014 274150878-NpOeStPeAdM@NnO wSlPiAnMkcom...
On 2007-11-30 14:03:41 -0800, "RSH" <wa************ *@yahoo.comsaid :
>[...]
But since I dont know the number of departments the system will
ultimately
contain, I dont want to hardcode the references in a conditional.

It's difficult for me to be sure I completely understand the question. I
don't find the description very organized. But, that said...

It seems to me that what you've got are already-existing instances of
ApprovalChain-derived classes that are somehow related to your
instantiation of the Purchase class. It appears you may also have a class
named "Budget" that also has derived versions you're using.

Given that, you may want to consider just storing those instances in a
Dictionary<T>, so that you can easily look them up according to their enum
value. For example:

enum Department
{
Acct, Mktg
}

struct DepartmentObjec ts
{
public readonly ApprovalChain ApprovalChain;
public readonly Budget Budget;

public DepartmentObjec ts(ApprovalChai n ApprovalChain, Budget
Budget)
{
this.ApprovalCh ain = ApprovalChain;
this.Budget = Budget;
}
}

static Dictionary<Depa rtment, DepartmentObjec tsdictDepartmen ts;

// run once somewhere (e.g. static constructor for whatever class
// contains the "dictDepartment s" object)
foreach (Department dept in Department.GetV alues())
{
switch (dept)
{
case Acct:
dictDepartments .Add(dept, new DepartmentObjec ts(new
AccountingAppro valChain(), new AccountingBudge t()));
break;
case Mktg:
dictDepartments .Add(dept, new DepartmentObjec ts(new
MarketingApprov alChain(), new MarketingBudget ()));
break;
}
}
// then wherever you need to match the enum to an instance, something
// like this:

Department dept = // initialized however...;

ApprovalChain approval = dictDepartments[dept].ApprovalChain;

// Or you could do this:
DepartmentObjec t do = dictDepartments[dept];
Purchase purchase = new Purchase(id, amount, description, dept,
do.ApprovalChai n, do.Budget);

etc.

Note that at some point you do need to hardcode the relationship between
your enum and the class each value represents. Depending on the actual
names you've used for things it certainly is possible to use reflection to
even automate that, but it seems to me it wouldn't really buy you much.
It's not like you can just go adding new ApprovalChain and Budget objects
without visiting the code that uses those objects and verifying you've
done everything right anyway (or at least you ought to be).

Pete

Nov 30 '07 #6

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

Similar topics

8
2734
by: mrbog | last post by:
This is a "namespace" problem with "::". Is there an official place I can report php bugs? I'm new to PHP (and soon to be leaving it): class SomeClass { function dostuff($ar) { uasort($ar, 'SomeClass::somesort'); } function somesort($a,$b) {<-- never gets called echo "Yes I got called"; //<-- never happens
2
2982
by: Ryan Mitchley | last post by:
Hi all I have code for an object factory, heavily based on an article by Jim Hyslop (although I've made minor modifications). The factory was working fine using g++, but since switching to the Intel compiler it has stopped working. I think the singleton pattern static instance thing may be at the root of the problem, but I'm not sure. I had to add calls to instance() in regCreateFn, which gets the behaviour more in line with what I was...
4
1698
by: Earl Teigrob | last post by:
In the exampe below, the constructor of the container class is passed the string called "foo". Within the container class, I would like to create an instance(s) of foo and add them to the ArrayList that is returned. (Once I figure this out I will use reflection on the instance to do other stuff) Anyway, How to I dyanamically create a new instance of a class from ClassName string? Thanks for your Help
2
2333
by: buran | last post by:
Dear ASP.NET Programmers, I want to store the referring page of an .aspx page so that I can redirect the user back to the referring page if needed. I am using the following code snippet but receiving Object reference not set to an instance of an object error. The code is as follows: If Not Page.IsPostBack Then Viewstate("ReferrerURL") = Request.UrlReferrer.ToString() LoadData()
1
1075
by: news.zen.co.uk | last post by:
Hi Guys, Am putting together a WEB App with an ever nearing deadline :o( I've a Master Datagrid (defined in the ASP page) containing in the second column a (details) datagrid (dynamically generated with the ItemDataBound event for the master). Got the basic code from the excellent article http://www.dotnetjunkies.com/Tutorial/47792CB0-0990-4BD8-BF84-B6063C4C9BBC.dcik Code frag as follows:
12
5560
by: Andrew Poulos | last post by:
With the following code I can't understand why this.num keeps incrementing each time I create a new instance of Foo. For each instance I'm expecting this.num to alert as 1 but keeps incrementing. Foo = function(type) { this.num = 0; this.type = type this.trigger(); } Foo.prototype.trigger = function() {
2
1559
by: Jerry Spence1 | last post by:
One way of passing data to a thread is to encapsulate the thread inside a class. However, I can't refer to my main form objects from within the class/thread as it says "Reference to a non-shared member requires an Object reference". How do I refer to items such as Textbox1.text etc on my main form? -Jerry
6
96252
NeoPa
by: NeoPa | last post by:
Introduction The first thing to understand about Sub-Forms is that, to add a form onto another form takes a special Subform control. This Subform control acts as a container for the form that you want to act as a Sub-Form of the main one. That is to say, if you wanted frmB to act as a Sub-Form of frmA, then you would create a Subform control on frmA (in this example we'll call it sfmB). Subforms have a .Form property which contains a...
1
1286
by: Revathi Priya | last post by:
how can i change the height and width of an iframe dyanamically... i mean how to access the height and width
0
9718
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10614
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10369
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10109
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...
0
9186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7649
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
6876
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
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3847
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.