Kerry White
Kerry White

Reputation: 416

C# List.Clear() clearing ALL Lists

I'm loosing my head on this one. I have two lists. When I clear one list, both lists are Cleared! I cannot find out where or why this is happening.

Here is my code:

Console.WriteLine("A: {0} \t As: {1}", Globals.Artists.Count(), Globals.ArtistsSelected.Count);
Globals.ArtistsSelected.Clear();
Console.WriteLine("A: {0} \t As: {1}", Globals.Artists.Count(), Globals.ArtistsSelected.Count);

The results from the above code is:

A: 121   As: 121
A: 0     As: 0

As you can see before the clear, Artists and ArtistsSelected both have 121 items. When I clear the one, the other one is cleared too.

Here is how the lists are declared:

public static List<string> Artists = new List<string>();
public static List<string> ArtistsSelected = new List<string>();

I only have one place that loads Artists and it doesn't get called again after that point, and No place at all looks like this: Artists = ArtistsSelected; or this: Artists.Clear().

Any help would be greatly appreciated! Oh, I also tried renaming ArtistsSelected to something like SelectedArtists and it still didn't phase it.`

* UPDATE *

Because some of you are asking, here is how Artists is loaded by calling:

public static void populateArtistList()
    {
        Globals.Artists = SQL_Read.getArtistList();
        Globals.SelectedArtists = Globals.Artists;
    }

Then here's the SQL part:

public static List<string> getArtistList()
    {
        List<string> artists = new List<string>();
        SqlConnection con = new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        string query = "SELECT Name FROM Artists ";

        con.ConnectionString = SQL_getConnectionString.conStr();
        con.Open();

        cmd.Connection = con;
        cmd.CommandText = query;

        SqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            artists.Add(reader.GetString(0));
        }

        con.Close();
        return artists;
    }

Upvotes: 1

Views: 2397

Answers (1)

Klinger
Klinger

Reputation: 4970

Globals.SelectedArtists = Globals.Artists; is your culprit.

Doing so makes both fields point to the same list instance.

What you need to do is the following:

Globals.SelectedArtists.AddRange(Globals.Artists);

Upvotes: 6

Related Questions