Trying to close all forms except for the main menu using
FormCollection formsList = Application.OpenForms;
with a foreach loop and saying,
as the form collection is updating for every iteration. When you close a form, it is removed from the form collection. it's like removing a object from memory while it is using .
Here's an even more concise method that uses the same number of lines as your original method:
Form[] forms = Application.OpenForms.Cast<Form>().ToArray();
foreach (Form thisForm in forms)
{
if (thisForm.Name != "Menu") thisForm.Close();
}
By using Linq's extension method Cast
, you can avoid looping through the collection to build an array.