Reputation: 530
So I have a dictionary:
var tableVars = new Dictionary<string, TableDLL.tableObject>();
And the tableObject class:
public class tableObject
{
public string Name { get; set; }
public string Type { get; set; }
public string Value { get; set; }
public string Default { get; set; }
}
And I go through this loop:
var obj = new TableDLL.tableObject();
foreach (XmlNode nodes in root.ChildNodes)
{
obj.Value = nodes.InnerText;
tableVars.Add(nodes.Name, obj);
}
When the loop is complete, I have 65 different Dictionary
entries, but they are all pointing to the LAST obj
that is made in the loop. What would be the best way to get the Dictionary
to store the value, rather than simply pointing to it (and therefore changing with changes to obj
)? Do I have to make a new TableDLL.tableObject
for each Dictionary
entry?
Upvotes: 0
Views: 79
Reputation: 13783
You've only created 1 object, so there is no possibility for the list to have 65 different objects.
Basically, what you did is:
You haven't created a new container, you just changed the existing container's contents.
Do it like this:
foreach (XmlNode nodes in root.ChildNodes)
{
var obj = new TableDLL.tableObject();
obj.Value = nodes.InnerText;
tableVars.Add(nodes.Name, obj);
}
The difference being:
If you want 65 tableObject
objects, you will need to call new tableObject();
65 times. Else you're just reusing the original object.
Feel free to ask for more information if you need it.
Upvotes: 2
Reputation: 21713
Create a new copy of your tableObject
each time round the loop.
foreach (XmlNode nodes in root.ChildNodes)
{
var obj = new TableDLL.tableObject();
obj.Value = nodes.InnerText;
tableVars.Add(nodes.Name, obj);
}
Upvotes: 1
Reputation: 50225
You're only creating a single object and continually updating Value
with the last node. With the correction, you're creating N objects with the appropriate Value
.
This:
var obj = new TableDLL.tableObject();
foreach (XmlNode nodes in root.ChildNodes)
{
obj.Value = nodes.InnerText;
tableVars.Add(nodes.Name, obj);
}
should be this:
foreach (XmlNode nodes in root.ChildNodes)
{
var obj = new TableDLL.tableObject();
obj.Value = nodes.InnerText;
tableVars.Add(nodes.Name, obj);
}
Upvotes: 3
Reputation: 460148
You just have to create it in the loop:
foreach (XmlNode nodes in root.ChildNodes)
{
var obj = new TableDLL.tableObject();
obj.Value = nodes.InnerText;
tableVars.Add(nodes.Name, obj);
}
Otherwise you're always adding the same object.
Upvotes: 2
Reputation: 499052
Move the creation of obj
into the loop:
foreach (XmlNode nodes in root.ChildNodes)
{
var obj = new TableDLL.tableObject();
obj.Value = nodes.InnerText;
tableVars.Add(nodes.Name, obj);
}
Otherwise you are adding the same object multiple times.
Upvotes: 3