danrodi
danrodi

Reputation: 296

Adding to list overwrites previous object values in C#

Although there are several posts on Stackoverflow about this kind of issue, then I have looked through them and have not found a solution for my problem.

In the code, I am going going through a list of lists with a foreach loop and adding created elements to another list. Although in the foreach loop each iteration gives an unique value, then outside of it the values are the same.

try
{
    List<Takeoff> takeoffs = new List<Takeoff>();

    List<List<String>> itemTable = queryTable("TK_ITEM", 52);

    foreach (List<String> row in itemTable)
    {
        // Second element in the constructor is Name.
        Takeoff takeoff = new Takeoff(row.ElementAt(0), row.ElementAt(3), row.ElementAt(11), 
            row.ElementAt(17), row.ElementAt(25), row.ElementAt(33), 
            row.ElementAt(37), row.ElementAt(45));

        MessageBox.Show(row.ElementAt(3)); // Each iteration gives an unique value.

        takeoffs.Add(takeoff);
    }

    // Values of both objects are the same.
    MessageBox.Show(takeoffs[0].Name);
    MessageBox.Show(takeoffs[1].Name);

    return takeoffs;
}
catch (Exception)
{
    MessageBox.Show("No material takeoff created!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);

    return null;
}

I have tried various methods of adding and displaying the values, but so far I have not found a solution which would work.

Could anyone point out to me where the problem is?

Edit: Declaration of takeoff

/*...*/
private static string name;
/*...*/

public Takeoff(string id, string name, string guid, string width, string height, string area, string volume, string count)
{
    /*...*/
    Name = name;
    /*...*/
}

/*...*/

public string Name
{
    get { return name; }
    set { name = value; }
}

/*...*/

Upvotes: 1

Views: 1476

Answers (1)

CodeCaster
CodeCaster

Reputation: 151594

Your name backing field is static:

private static string name;

Don't do that. Just remove the static modifier, it's not necessary.

Static members belong to the type, rather than the instance. This means all instances of Takeoff share the same value of name, whichever value was assigned last.

Upvotes: 8

Related Questions