user2760129
user2760129

Reputation: 161

Clear all LIST <> each time click the button?

Is there any way to clear all the list items in short way instead using List.Clear(); method for each of them? Because when I click my button first time I stored some items inside my list and when I click my button second time it suppose to get new items, but it still holding the old items not the new ones... I think clearing all the list right after click the button and start storing items inside my list would help me to get solved this problem...

I have below classes:

Fruits
vegetables
cars
Homes
.
.
.

Upvotes: 1

Views: 1242

Answers (2)

Servy
Servy

Reputation: 203811

The solution to your problem is simply to not have the lists in the first place.

Rather than having these static methods be void and sticking their results in static lists that need to be cleared each time they are called, you should instead have then return their values, like so:

public static List<string> GetFruits()
{   
    var list = new List<string>();

    OracleConnection conn1 = MyConnection.GetSourceConnection();

    conn1.Open();  
    using (OracleCommand storeFruits = new OracleCommand("MyCOMMAND", conn1))
    {
        using (OracleDataReader reader = storeFruits.ExecuteReader())
        {
            while (reader.Read())
            {
                list.Add((string)reader["TABLE_NAME"]);
            }
        }
    }

    return list;
}

This has a number of advantages:

  1. You can call the method concurrently without any concerns, since each caller has their own list.

  2. There is no worry about clearing the lists, ever. You start fresh every time.

  3. There is no worry about a list that one caller is using being modified as a result of some other call in some other location. Each caller only needs to worry about their code, not everyone else's.

Upvotes: 2

iabbott
iabbott

Reputation: 881

If they are all private lists you will not be able to see them from another class

Even if you made them public static you would still have to do:

Class1.myLIST1.Clear();
Class2.myLIST2.Clear();
// etc

Upvotes: 0

Related Questions