Create a new instance of a class that is a reference

Hi all,

I am trying to make a class that when you create a 2nd instance the second instance will be a reference to the first.

Public Class ClassA
    Private Shared tableList As Hashtable
    Public myInt as integer = 0

    Public Sub New()
        MyBase.New()
        InitializeValues()
    End Sub
    Private Function openTable() As Boolean
        If (tableList Is Nothing) Then
            tableList = New Hashtable()
        End If

        If (tableList.ContainsKey(TABLE)) Then
            SetReference(Me, tableList(TABLE))
            OpenCount += 1
        Else
            OpenCount += 1
            tableList.Add(TABLE, Me)
        End If
    End Function
    Public Shared Sub SetReference(ByRef obj As Object, ByRef newObj As Object)
        obj = newObj
    End Sub
End Class

Public Sub Test()
    Dim myClass1 as new ClassA
    Dim myClass2 as new ClassA

    'set myInt = 200 for both
    myClass1.myInt = 200
End Sub




Submitted via EggHeadCafe - Software Developer Portal of Choice 
ASP.NET Cookies FAQ
http://www.eggheadcafe.com/tutorials/aspnet/198ce250-59da-4388-89e5-fce33d725aa7/aspnet-cookies-faq.aspx
0
Jeremy
12/7/2009 7:10:53 PM
dotnet.languages.vb 830 articles. 0 followers. Follow

3 Replies
734 Views

Similar Articles

[PageSpeed] 57

Jeremy Benenati schrieb:
> Hi all,
> 
> I am trying to make a class that when you create a 2nd instance the second instance will be a reference to the first.
> 
> Public Class ClassA
>     Private Shared tableList As Hashtable
>     Public myInt as integer = 0
> 
>     Public Sub New()
>         MyBase.New()
>         InitializeValues()
>     End Sub
>     Private Function openTable() As Boolean
>         If (tableList Is Nothing) Then
>             tableList = New Hashtable()
>         End If
> 
>         If (tableList.ContainsKey(TABLE)) Then
>             SetReference(Me, tableList(TABLE))
>             OpenCount += 1
>         Else
>             OpenCount += 1
>             tableList.Add(TABLE, Me)
>         End If
>     End Function
>     Public Shared Sub SetReference(ByRef obj As Object, ByRef newObj As Object)
>         obj = newObj
>     End Sub
> End Class
> 
> Public Sub Test()
>     Dim myClass1 as new ClassA
>     Dim myClass2 as new ClassA
> 
>     'set myInt = 200 for both
>     myClass1.myInt = 200
> End Sub

Even with looking at the code, I'm not sure what's your real intention. If it's what you wrote
above, it doesn't makes sense. Each instance is unique. If you have two instances, there are two
instances - surprise. You can make one instance point to another one, or you can have more
references pointing to the same object.

What if you create 3 instances?

If you only want to have one instance at all, you may consider using shared members only.

As "TABLE" is not declared anywhare, I suppose it is meant to be an argument of openTable.
Then I think, you want to have only one instance per TABLE. So maybe it's something like this:

   Class classA
      Private Shared tableList As New Hashtable

      Public Shared Function openTable(ByVal Table As String) As classA

         If tableList.ContainsKey(Table) Then
            Return DirectCast(tableList.Item(Table), classA)
         Else
            Dim result = New classA
            tableList.Add(Table, result)
            Return result
         End If

      End Function
   End Class



-- 
Armin


0
Armin
12/7/2009 7:39:16 PM
On 2009-12-07, Jeremy Benenati <Jeremy> wrote:
> Hi all,
>
> I am trying to make a class that when you create a 2nd instance the second instance will be a reference to the first.
>
> Public Class ClassA
>     Private Shared tableList As Hashtable
>     Public myInt as integer = 0
>
>     Public Sub New()
>         MyBase.New()
>         InitializeValues()
>     End Sub
>     Private Function openTable() As Boolean
>         If (tableList Is Nothing) Then
>             tableList = New Hashtable()
>         End If
>
>         If (tableList.ContainsKey(TABLE)) Then
>             SetReference(Me, tableList(TABLE))
>             OpenCount += 1
>         Else
>             OpenCount += 1
>             tableList.Add(TABLE, Me)
>         End If
>     End Function
>     Public Shared Sub SetReference(ByRef obj As Object, ByRef newObj As Object)
>         obj = newObj
>     End Sub
> End Class
>
> Public Sub Test()
>     Dim myClass1 as new ClassA
>     Dim myClass2 as new ClassA
>
>     'set myInt = 200 for both
>     myClass1.myInt = 200
> End Sub
>

I'm not sure I really understand what your after here...  But, it sort of
sounds like a singleton pattern.  The common way to do that would look
something like:

Public Class ClassA
	Private Shared _instance As New ClassA()
	Public myInt As Integer = 0

	' constructor is private so you can't create
	' outside references
	Private Sub New()
		InitalizeValues()
	End Sub

	Public Shared ReadOnly Property Instance()
		Get
			Return _instance
		End Get
	End Property
End Class

Public Sub Test
	Dim myClass1 As ClassA = ClassA.Instance()
	Dim myClass2 As ClassA = ClassA.Instance()

        myClass1.myInt = 200
	Console.WriteLine (myClass2.myInt)
End Sub


-- 
Tom Shelton
0
Tom
12/7/2009 7:54:12 PM
You do that when you instantiate the class, not when you create the class 
design.

Public Sub Test()
   Dim myClass1 as ClassA = New ClassA
   Dim myClass2 as ClassA = myClass1

   'set myInt = 200 for both
   myClass1.myInt = 200
End Sub

"Jeremy Benenati" wrote in message news:2009127141051jcbenenati@yahoo.com...
> Hi all,
>
> I am trying to make a class that when you create a 2nd instance the second 
> instance will be a reference to the first.
>
> Public Class ClassA
>    Private Shared tableList As Hashtable
>    Public myInt as integer = 0
>
>    Public Sub New()
>        MyBase.New()
>        InitializeValues()
>    End Sub
>    Private Function openTable() As Boolean
>        If (tableList Is Nothing) Then
>            tableList = New Hashtable()
>        End If
>
>        If (tableList.ContainsKey(TABLE)) Then
>            SetReference(Me, tableList(TABLE))
>            OpenCount += 1
>        Else
>            OpenCount += 1
>            tableList.Add(TABLE, Me)
>        End If
>    End Function
>    Public Shared Sub SetReference(ByRef obj As Object, ByRef newObj As 
> Object)
>        obj = newObj
>    End Sub
> End Class
>
> Public Sub Test()
>    Dim myClass1 as new ClassA
>    Dim myClass2 as new ClassA
>
>    'set myInt = 200 for both
>    myClass1.myInt = 200
> End Sub
>
>
>
>
> Submitted via EggHeadCafe - Software Developer Portal of Choice
> ASP.NET Cookies FAQ
> http://www.eggheadcafe.com/tutorials/aspnet/198ce250-59da-4388-89e5-fce33d725aa7/aspnet-cookies-faq.aspx 

0
James
12/7/2009 11:25:05 PM
Reply:

Similar Artilces:

how to creat other inbox
i have 3 different email account and i want each to receive in difference any can help please You can create other 'fake' inboxes for each and use rules to move inbound messages therein. Methods and features depend on the version of Outlook, which you haven't posted.... Akbar uk wrote: > i have 3 different email account and i want each to receive in > difference any can help please ...

Create window that always stays as taskbar button
Hi, I'd like to create an extra window from my application that has a taskbar button always stays in the taskbar. So i derived a class from CFrameWnd and create it with WS_EX_APPWINDOW style However, the problem is the extra new window will become hidden and disappeared from taskbar when my main application window is being minimized. It appears on taskbar again only when the main app's windows is being restored or shown. How could i prevent the extra windows from being disappeared from the taskbar button? Please kindly advise. thank you very much Jeffrey when you stay taskbar bu...

Crosstab Query with query parameter used to create a report
My crosstab query using a query parameter works fine; however, once I try to use it to create a report I am asked multiple times to re-enter my query parameters. The report generates the correct results; however, why do I need to re-enter my query parameter multiple times?? Thanks.. Open the crosstab in design view, click on menu Query - Parameters. This opens another window. Type in your parameter names and data type. Save. -- KARL DEWEY Build a little - Test a little "JJ_Access" wrote: > My crosstab query using a query parameter works fine; however, once I try to ...

new user
kindly forward me the essentials of using this program "shibinboban" <shibinboban@yahoo.co.in> wrote in message news:OwEgh1eeIHA.148@TK2MSFTNGP04.phx.gbl... > kindly forward me the essentials of using this program http://office.microsoft.com/en-us/access/FX100487571033.aspx -- Albert D. Kallal (Access MVP) Edmonton, Alberta Canada pleaseNOOSpamKallal@msn.com ...

How do I create an original logo WITHOUT design gallery objects ?
I want to create an original logo but do not like any of the existing styles in the design gallery. how do I create a new one? changing the elements in a design gallery object is too restrictive. what format do I open to create such a design? Publisher has an array of auto shapes, a simple logo is best. Experiment with different shapes. A draw program. DrawPlus is free. http://www.freeserifsoftware.com/ -- Mary Sauer http://msauer.mvps.org/ "libbybolt" <libbybolt@discussions.microsoft.com> wrote in message news:FC71CBB0-B2C9-4488-8063-8D3689448DA5@microsoft.com.....

Need to up date refereences from Ofice 2002 to 2007
I had vs2008 and Office 2000 or maybe 2002 installed. I rebuilt my system and installed Office 2007 instead. Now when I try to compile I get the errors shown below. I guess I need to add a couple of references and do see many for Office but can't identify the ones I need. I also hav a sneaking suppesion it's not that simple. Can you help get this fixes? Warning 1 The referenced component 'Microsoft.Office.Core' could not be found. Warning 2 The referenced component 'Microsoft.Office.Interop.Word' could not be found. Warning 3 The referenced...

Creating a botton to update data from a Form to Table
Greetings People I need to know how to create a botton on a Form (Microsoft Access) that may allow me to update the data in a Table. I know that I have to use VBA or VB ..NET CODE to create it. Where could I find a sample code that may help me with that? Reboot Kid On Tue, 11 May 2010 16:19:01 -0700, Reboot the Kid <ReboottheKid@discussions.microsoft.com> wrote: >Greetings People > >I need to know how to create a botton on a Form (Microsoft Access) that may >allow me to update the data in a Table. I know that I have to use VBA or VB >.NET CODE to c...

error after re-creating a mailbox
task 'Microsoft Exchange Server' reported error (0x80070005): 'You don't have appropriate permission to perform this operation' ...

How to create the email account when I have more than one hotmail account?
Dear sir, Have any one can help me? I was using outlook express previous. I can create more than one email account for my several hotmail accounts. However, I recently want to use outlook. So, I went to set up some email accounts in the outlook. But I encountered some problems that I don't know how to caret more email accounts for my the other hotmail accounts. I only can create one email account for hotmail account. Best Regards, Wayne Hy Wayne, please read this here http://home.arcor.de/andreas.roeder-privat/English%20Help.htm#9 -- Ich habe nichts gemacht, gestern gings noch! Bit...

DPM was unable to attach the content database to the SQL Instance
Hello, I'm trying to restore a document back to my SP Farm using Recovery Farm which but I get the message that is is unable to attach the content database. I checked the errlog on the Recovery Farm server for DPM and see this genericstatus.cpp(1089) [00000000007BB1 |TaskID=8C81A792-FF26-4BE3-8633-DF4FDB8DEF8F Failed: Unable to open the QFE registry key [Software\Microsoft\Updates\Windows Server 2003\SP3\VSS\KB940349]: 0x80070002 vadatasourcestate.cpp(651) |TaskID=EF05DA88-B436-4C96-B939-7E1DD76339D9 GetModuleHandle failed for Library [WSSWriterHelperPlugin], Hr = [0x800...

New line in a cell
During writing text in a cell, I would like to make new line instead of continuing writing. For example, a new paragraph. Can anyone help? Abe Use <Alt><Enter>. You may have to drag the column wider to get the proper length of the line. -- Best Regards Leo Heuser Followup to newsgroup only please. "Abe" <Abe@discussions.microsoft.com> skrev i en meddelelse news:A670ADE7-A526-415F-AAC1-7806836E9EA7@microsoft.com... > During writing text in a cell, I would like to make new line instead of > continuing writing. For example, a new paragraph. > > Can ...

creating an index for multiple pages within a visio document?
I have a visio document with about 50 drawings in it. Is there an automated way to create an index from the name of each drawing? Thanks Carol in Roy WA There used to be an add-on "table of contents" but I have not it used in years in earlier versions, but try searching for it. "clemonwa" <clemonwa@discussions.microsoft.com> wrote in message news:B9728AA5-1529-41AC-940C-B275C9D5A1E7@microsoft.com... >I have a visio document with about 50 drawings in it. Is there an >automated > way to create an index from the name of each drawing? > > Thanks &g...

How to attach a menu to the CDialog class?
Hi,All: I tried to attach a menu to the CDialog class from the "Resource Edit" tool,but it's so strange,when I show the CDialog class,it did not showed up,can anybody tell me how to do it?thanks in advance. Carl Hi First of all prepare the menu resource: add a new menu resource into the resources and design its items as you like. Then go to the dialog editor, open Properties window and select the newly created menu`s id for Menu peoperty. Even though possible I would not advice pursuing this design. It just opens a can of worms, since you will have to add command handling...

New Mail Desktop Alert...
I don't see it - why?! I have all the settings set (under 'advanced email options' the NMDA box is checked, and I have selected 'show new mail desktop alert' in the systray icon menu). They always worked in the Beta (which was never installed on this system), but I've never got them to work in the full version - and they were one of the reasons I purchased it - that and the reading pane. In addition, this is the default account, as it's the only account I have. I have it set to auto send/receive every 5 minutes, and keep OL minimised to the systray (ahem, notifica...

Open form with selected records
I am trying to open my form from a splashscreen and only show records that have a blank date field. My form always opens without any records. I have at least 30 in the table. I tried opening from a query that I use to list these records on a report but then I cannot add new records. Open the form in design view and check its properties. If the form opens without records, it may have the Data Entry property set to Yes (providing a form for entering new data, but not showing existing). Another approach, and one that saves loading all the available records "behind the form", w...

Deluxe 8oz Black Popcorn Maker Machine by Paramount Entertainment
List Price:$499.99 Image: http://bestdeallocator.info/image.php?id=B001CSE7FS Best price found: http://bestdeallocator.info/index.php?id=B001CSE7FS NOTICE: Popcorn Machines also available in other Colors, Sizes, & with or without Cart. (Simply click "Other products by Paramount-Entertainment" above or click >here Product Features - Condition: Brand New - Warranty: Five (5) Year - Eight (8) Ounce Stainless Steel Rotational & Detachable Kettle - 860 Watts - Built-In Electric Stirring System - Low-Noise Motor & Gearbox (Upgraded Metal Gears) ...

How to change a formula reference?
I need to create a formula that references a range of cells. The range is supposed to be determined by what the user enters into another cell. Can a formula have a variable in it that will grab a number from another cell? For instance: =COUNTIF(N[B18]:N[B18+B18],"Y")? Where you see B18 the user has entered in a number, we will say it was 5. I need the function to reference the cells in the N column from N5 (cell B18 has a 5 in it) to N10 (B18+B18 or 5+5). I appreciate any help you all can give me. Thanks so much in advance. Brockettb Hi! Assume you enter in cells: A1 = 5...

How to create SQL logins in FIPS compliant environment ?
Hi, our objective is to make our application FIPS compliant. One of the procedure accepts username and password as parameters and does a CREATE LOGIN call. But with FIPS, if we pass the password to the procedure in clear text format, it will be a violation. Can you suggest any other method of passing the password to the procedure and still be FIPS compliant? Or any other way to achive the same result? Also want to know that when SQL Server Management Studio opens a connection using sql user and password, how is the password sent to the SQL Server? Is it in clear text? In oth...

Something new
Hi, I have something weird on my worksheet. In the upper left of the worksheet, I have two small buttons with the numbers 1 & 2 on them. They are just to the left of the column headers. I do not have any sub totals so I do not know what they mean. can someone tell me what they are and how to get rid of them. Thanks Sounds like you have some grouped rows. Select all cells, goto Data>Group and Outline.. and ungroup them -- HTH Bob Phillips ... looking out across Poole Harbour to the Purbecks (remove nothere from the email address if mailing direct) "TO" <...

Export cells and creat word document
What I need to do is take the contents of cells in two columns and export or save them to automatically create a word document. The content of cell in first column would become a Heading 2 in word document and content of cell in second column would be normal text below the Heading 2. When the html tag <br><br> is found this would become a new paragraph. This would continue until all cells have been converted. Page Title Page Text 1. Title 1 text This is text for content under title 1 2. Title 2 text This is text for content under title 2<br...

How to create user form from scratch
Hi folks, I need to create a user form where they will be able to pick one of the status (Pending, Complete, Incomplete, Beyond). These 4 status will be displayed using option buttons.After the user chooses the status, i need the selected status to be displayed on the cell. (K4) I have no idea as to even start doing this. I really hope there is someone kind enough to teach me step by step on how to accomplish this. Please supply coding if there is any. Thanks a lot. Check Debra Dalgleish's site: http://contextures.com/xlUserForm01.html Tom Ogilvy posted these links: Peter Aiken Articl...

How to create an open dialog (CFileDialog) with thumbnails style?
Hi, anyone knows how to create an open dialog (CFileDialog) with thumbnails style. Best Regards, ZHANG Liren Here is how to do it. http://msdn.microsoft.com/msdnmag/issues/04/03/cqa/default.aspx?fig=true#fig2 Simply pass ODM_VIEW_THUMBS to SetListView in the OnInitDialog this is the actual article: http://msdn.microsoft.com/msdnmag/issues/04/03/cqa/default.aspx AliR. "zhanglr" <zhanglr@discussions.microsoft.com> wrote in message news:4FD81056-BC57-4148-8572-9D29DBC7E12B@microsoft.com... > Hi, > > anyone knows how to create an open dialog (CFileDialog) with thumb...

How can I create a multiple field search box? (corrected post)
Hi, I need assistance in creating a multiple field search box, i have a screen shot but i couldn't find a way to include it in this message. I have been battling with this problem for weeks. the search box was created in foxpro, i'm trying to create a similar search box in ms access 2003. it searches only one table so each table has a search box for it. Here is a description for the search box for the community table which is one of the tables in the database. It has a drop down list that selects all the fields in the table such as area code for the community, community code, and com...

How tu create an entity programmaticaly?
Hi, I have a lot of entities to create and I take so much time to create one with the crm web interface that I wondered if it is possible or not to create a script or a .net program to create my entities. Anyone has already done that or knows if it is possible or not? Thanks Yes it is possible. See this thread: http://groups.google.com/group/microsoft.public.crm.developer/browse_frm/thread/f95e8e74cb874fd/e879eade0ec3f823?lnk=st&q=create+entities+using+web&rnum=1#e879eade0ec3f823 HTH, -- Jeffry van de Vuurst CWR Mobility www.cwrmobility.com -- "Hasan Ozdil" <hasan....

Disappearing column totals in cross-reference table query
I have added column totals in a cross-reference table query, by clicking Registers/Totals. I saved the query and closed it. (I'm using a Portuguese version of MS Office and apologise if my translation of the commands is not perfect.) Whenever I open the query again, the totals have disappeared. I have to activate them again by clicking on Registers/Totals. This doesn't happen in a simple query. The column totals I add remain activated, and are visible when the query is opened the next time. I would be grateful for any help. Matias ...