I’m using .Net 2.0 and this is driving me crazy but there’s probably some easy thing I’m not doing that I am now too confused to see.
I have an application that has a bespoke collection of objects in it, only the main form should be able to change the contents of that collection and all other forms should be able to read from it.
Actually there’s only one other form but I need it to have the capability of being called multiple times as it edits different items in the bespoke collection. To make the child form a dialog is therefore impractical. The ability to open multiple instances of this form containing different items from the collection is necessary.
I just can’t seem to think of a way of making all forms revolve around the same instance of the collection. Like I say I’m probably missing something obvious but I have ceased to be able to think about the problem properly.
EDIT: Yikes! I can’t have explained myself very well. All subforms should be able to read and write collection items, but I want to only use one instance of the collection at a time whilst the programme is running.
EDIT 2: It turned out that what I needed was a singleton. I have implemented a similar solution in a different project now. Thanks to the commenter below who didn’t actually leave an answer I can mark as the correct one, even though they nailed it.
If the main form needs read/write access but other forms don’t, then I would make the collection a property of your main form that is read/write from within your form, but read only from outside your form. You can do this using something like:
C#
VB
Then you can reference your collection from inside your form by referencing either MyCollection or _MyCollection as you choose, but from outside your form, the collection will be ReadOnly and therefore not editable.
Edit: After your edit, it does look like what you’re after is a singleton as previously suggested does this mean that all instances of your forms should be able to edit this collection or not? If so, then put your collection into a static class:
Now the first time the collection is referenced from within one of your forms it will instantiate a new collection which you can then add/remove items from. Every time you reference the collection from this or one of your other forms, it will already have been instantiated, so it will return the collection that was originally instantiated. None of the forms however will have the ability to set a new collection, just reference the one instantiated by the singleton pattern.