WorkerBee
WorkerBee

Reputation: 19

Unexpected results reading a C# List of NameValueCollections

I add three NameValueCollections to a List of NameValueCollections. When I read the NameValueCollections records back from the List and retrieve the values, I expect to see the three different values but instead each of the three returns the value of the third record ( the last record added ). Please could someone de-confuse me? I seem unable to figure it out myself. The (simplified) code below demonstrates my problem...

NameValueCollection record = new NameValueCollection();

List<NameValueCollection> records = new List<NameValueCollection>();

record.Clear();
record.Add("recId", "first record");
records.Add(record);
page += "<p>Added record: " + records[0]["recId"] + "</p>";

record.Clear();
record.Add("recId", "second record");
records.Add(record);
page += "<p>Added record: " + records[1]["recId"] + "</p>";

record.Clear();
record.Add("recId", "third record");
records.Add(record);
page += "<p>Added record: " + records[2]["recId"] + "</p>";


//-- OUTPUT ------------
foreach (NameValueCollection rec in records)
{
    page += "<p>rec.get(\"recId\") = " + rec.Get("recId") + "</p>";
}

Output:

Expected:
rec.get("recId") = first record
rec.get("recId") = second record
rec.get("recId") = third record*

Actual:
rec.get("recId") = third record
rec.get("recId") = third record
rec.get("recId") = third record

Upvotes: 1

Views: 44

Answers (0)

Related Questions