473,771 Members | 2,406 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get class instance dynamically

6 New Member
Dear all,

I have a problem where I need to re-use the same instance of several classes over and over in my application. Like collections classes.

Is there a way, with reflection for example, of finding out at runtime if an instance of a class already exists and then using that instance?

Or do I have to create Singleton's for each of those classes?

Should I make a class that keeps track of all my other class instances? Is there maybe a pattern to do so?

Thanks in advance for any help.
Aug 21 '09 #1
7 2542
tlhintoq
3,525 Recognized Expert Specialist
If you only need ONE instance of a class, like a collection, you could make it STATIC and just use it with a variable that has global scope.
finding out at runtime if an instance of a class already exists
If it does exist didn't you have to assign it *to* something? Wouldn't you just check whatever variable you would have assigned that instance to?
Aug 21 '09 #2
tb2500
6 New Member
Ok on the first bit. Yes I could make it static. The problem is that I need this instance in several other different classes then where it was created.

So

Expand|Select|Wrap|Line Numbers
  1. Class A
  2. {
  3.      /// Some methods
  4. }
  5.  
  6. Class B
  7. {
  8. A = new A();
  9. a.DoSomething();
  10. }
  11.  
  12. Class C
  13. {
  14. // need same instance of A that B created... 
  15. }
You see what my problem is? An I have like 10 classes where I would need a particular instance of this one class?

@tlhintoq
Yes, but that variable is in another class as above.
Aug 21 '09 #3
Markus
6,050 Recognized Expert Expert
Hmm, they'd have to be singletons, no? Also, one class creating a concrete instance of another class breaks encapsulation, doesn't it (unless the object is passed in as an argument)?
Aug 21 '09 #4
tb2500
6 New Member
I agree Markus, I think that I would need to implement the Factory pattern or some such to get around my problem. Unless there's another way?
Aug 21 '09 #5
GaryTexmo
1,501 Recognized Expert Top Contributor
What I took from what tlhintoq said was make a public class with a public static member that you can access...

Expand|Select|Wrap|Line Numbers
  1. public class GlobalContainer
  2. {
  3.   public static A MyA = new A();
  4. }
then...

Expand|Select|Wrap|Line Numbers
  1. Class B
  2. {
  3. //A = new A();
  4. //a.DoSomething();
  5. GlobalContainer.MyA.DoSomething();
  6. }
  7.  
  8. Class C
  9. {
  10. // need same instance of A that B created...
  11. GlobalContainer.MyA.<whatever>
  12. }
To be honest, I don't know what a singleton is... wikipedia seems to suggest that it's basically what I just wrote. I don't know what this has to do with "the Factory pattern" though...

Hopefully I've been of some help. Good luck!
Aug 21 '09 #6
tlhintoq
3,525 Recognized Expert Specialist
Expand|Select|Wrap|Line Numbers
  1. Class B
  2. {
  3. A = new A();
  4. a.DoSomething();
  5. }
Shouldn't this be
Expand|Select|Wrap|Line Numbers
  1. A a = new A(); // so that a is a new instance of A so you can 
  2. a.DoSomething();
  3.  
Aug 21 '09 #7
tlhintoq
3,525 Recognized Expert Specialist
What about this? Make lists of your classes at program level so all can see.

Expand|Select|Wrap|Line Numbers
  1. Class Program()
  2. {
  3.     List<A> myAs = new List<A>;
  4.     List<B> myBs = new List<B>;
  5. }
Then add to those lists:
Expand|Select|Wrap|Line Numbers
  1. Class A
  2. {
  3.      /// Some methods
  4. }
  5.  
  6. Class B
  7. {
  8.    A newA = new A();
  9.    newA.CreatedByProperty = "B";
  10.    program.MyAs.add(newA);
  11.    newA.DoSomething();
  12. }
  13.  
  14. Class C
  15. {
  16. // need same instance of A that B created... 
  17.     program.MyAs[MyAs.Count-1]   {blah blah}
  18. // The most recently added 'A' is the last one in the list
  19. }
Now you have a List<> for each class that any other class can access.
You can add and search properties that let you know what type of class created it.
If you need to know any 'A' already just check the List<> MyA's.
If there is more than zero in the count, then an A exists.
If you need to know who made the existing 'A', check the CreatedBy property of each 'A' in the list
Aug 21 '09 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

3
2570
by: Robert Oschler | last post by:
Hello, I am a Python newbie (by experience, not chronologically :) ), so if any of this doesn't make sense my apologies in advance. I am reading the chapter in The Python Cookbook on databases and the MySQLdb module. In it they show an example of a recipe that lets you access fields in a MySQL row by name rather than by column number. For example, given a MySQL row object from a fetchone() call:
0
1695
by: Peter | last post by:
I use dynamically loaded dll's a lot in my programs. The one thing i cannot figure out how do is too to sucessfully pass the address of a class instance created within the dynamically loaded dll. I step thru the code and confirm that the class is correctly created in the dll, but as soon as it steps out of the dll i loose the address. For example: hLib = LoadLibrary("RasterIO.dll"); ImageIOClass *ImageIO = (ImageIOClass...
166
8674
by: Graham | last post by:
This has to do with class variables and instances variables. Given the following: <code> class _class: var = 0 #rest of the class
9
11577
by: keith | last post by:
I created a class libery which has name space Assembly and class Assembly and compiled it. Then created a C# project and called a method in the external class e.g. Assembly dll; dll=Assembly.LoadFrom(@"c:\app\Assembly.dll");
7
1762
by: Buddy Ackerman | last post by:
I created this class Public Class HTMLFileInput : Inherits System.Web.UI.HtmlControls.HtmlInputFile Public Property Data As String Get Return ViewState("HTMLFileInput.Data") End Get Set (ByVal Value As String)
9
1863
by: sashang | last post by:
Hi I'd like to use metaclasses to dynamically generate a class based on a parameter to the objects init function. For example: class MetaThing(type): def __init__(cls, name, bases, dict, extra_information): super(MetaThing, cls).__init__(name, bases, dict)
2
1949
by: wilkinson.philip | last post by:
I have a javascript object which dynamically generates a table adding, deleting and moving rows as the user clicks on buttons or links. Problem is when I generate a table row and add the javascript method call to my class, I have to put the object instance name variable of the class in order for it to be called from the onclick=function(). This is seriously limiting, but I'm stuck for a way round it. Heres a edited of the code so you get...
6
2039
by: jeff_j_dunlap | last post by:
Hello, Whenever I need class wide access to an object, I declare it dynamically: class myClass { ... myObject* obj; // declared dynamically ...
19
6075
by: =?Utf-8?B?Sko=?= | last post by:
I have a logging component that I will access in other assemblies. So it was brought up to me that I should pass an instance around to these components instead of just making the logging class static. If I make it static I wouldn't need to pass an instance around. What is your take on this?
4
2688
by: =?Utf-8?B?SmVzc2ljYQ==?= | last post by:
Hi All, I know that I can use the GetProcAddress to get the proc address of a global exported function from a WIn32 dll. But if I have an exported class in the dll, is there a way to dynamically load this dll and get an instance of this class? (No static linking with the lib file) I am currently thinking about having global exported functions which internally calls the member functions of the class's single instance. These global...
0
9619
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
9454
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
10261
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
10038
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
9911
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
8934
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...
0
6713
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3609
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.