I am writing a sort of image processing program that allows the user to open as many images as they want. Everytime the user opens an image the program has to create an object for it, which is defined by some class MyClass.
Obviously, when I create this object within the method of “opening the image” (e.g. clicking a menu button File -> Open…) the object is only known within this method and will be useless to other methods of the UI. I could create an array within the UI class and then just assign the object to MyClass[i] and keep counting up i, but that is not an option as I can’t know how many images the user wants to open. Also the user has to be able to close images again, which means that this index i will be useless.
Is there a way to somehow have a collection of objects to which I can add and remove objects dynamically? The objects have to be able to identify themselves within this collection by lets say the filename.
I am quite new to C# so please try to explain everything as detailed as possible.
What you need is a dynamic data structure like a List.
You can use either the generic (i.e. List) or the non-generic (i.e. List) version. With a List your are able to dynamically add or insert items, determine their indices and to remove items as you like.
The size of the list grows/shrinks dynamically as you are using the lists operations.
Suppose your images are represented as objects of type Image then you can use a List like that:
Alternative approach by using Dictionaries: