7
Answers

C#: Alternative Method to Static Objects

David Richardson

David Richardson

13y
2.7k
1
So I'm working on a project and have hit a logic roadblock in my design of it.

Currently I have several forms, and classes. I have one form MainForm handles the main window of my program. Inside this class, I have a static ArrayList of type "Room".
    public partial class MainForm : Form
   
{
       
public static ArrayList rooms = new ArrayList();
       
...
   
}


On load, MainForm will read in a list of items from a text file, and create "Room" objects and store them in an arraylist.
        public void loadSettings()
       
{
           
string path = System.IO.Path.Combine(Environment.CurrentDirectory, "config/Rooms.cfg");
           
string currentLine;
           
StreamReader read = new StreamReader(path);

           
while ((currentLine = read.ReadLine()) != null)
           
{
               
String[] parts = currentLine.Split(';');

               
string name = parts[0];
               
string video = parts[1];
               
string isLogged = parts[2];
               
string notify = parts[3];
             
                rooms
.Add(new Room(name, video, isLogged, notify));
           
}


The problem I am running into, is later on, I want to be able to manipulate this rooms array from another form, duely named "AddRoom", so I have done something like this:

 //In AddRoom.cs 
       
MainForm.rooms.Add(new Room(textBoxRoomName.Text));
       
MainForm.SaveAllRooms();

 
//In MainForm.cs
         
public static void SaveAllRooms()
       
{
           
TextWriter tw = new StreamWriter(Environment.CurrentDirectory + "/config/Rooms.cfg");
           
           
foreach(Room room in rooms)
           
{
                tw
.WriteLine(room.name + ";" + room.videoFeed + ";" + room.isLogged + ";" + room.notify);
           
}

            tw
.Close();
            populateListOfRooms
(); //THIS IS WHERE MY LOGICAL ISSUE IS
       
}


The problem is, in populateListOfRooms() I want to save the name of each Room in the arraylist rooms to an item in a Combobox.
Because of the fact that SaveAllRooms() and Arraylist rooms are both static, I can not access the specific instance of MainForm
in order to add items to the Combobox.

So I guess essentially my question is, since I can not use a static Arraylist object to store the room data, how can I go about storing these objects in a manner that is accessible from other forms, yet still allows me to access objects in the MainForm (like comboboxes).

I know this post was probably confusing, and definitely longer than it probably need have been, but it's late and so I apologize for any confusion.
Answers (7)