saamii saamii - 5 days ago 5
C# Question

Own class object attribute get overiden

I have a weird Problem.
I have created an object with the attributes String, and the other is a

List<String>
.
I have also created a
static List<MyObject>
where i add then all my Objects.
Now my Problem is the second attribute is getting overridden.

For Example i have 3 Objects:

Object1: "Name"; List with 3 Strings
Object2: "Name2"; List with 2 Strings
Object3: "Name3"; List with 5 Strings


If i add them now to my Object List, it looks like so

Name; List with 5 Strings
Name2; List with 5 Strings
Name3; List with 5 Strings


It override the second attributes to all the other Objects in the List.

Code:

for (int i = 0; i < 100; i++)
{

if (elo.ReadObjMask(i) > 0)
{
var iRet = elo.PrepareObjectEx(0, 0, i);
maskenname = elo.ObjMName();
if (maskenname != "")
{
for (int e = 0; e < 50; e++)
{
string eigenschaft = elo.GetObjAttribName(e);

if (eigenschaft != "" && eigenschaft != "-")
{
eigenschaften.Add(eigenschaft);
}
}
allMasks.Add(maskenname);

}

else
{
// Do nothing
}
EloMask emask = new EloMask(maskenname, eigenschaften);
staticVariables.allMask.Add(emask);
eigenschaften.Clear();
}
}


Thank you in advance!

Here is my Object Class:

public class EloMask
{
public string name;
public List<String> eigenschaften;


public EloMask(string iname, List<String> ieigenschaften)
{
name = iname;
eigenschaften = ieigenschaften;


}

}

Answer

The List<string> always points to the same instance because you are passing a reference to the list, not a copy. As a result, the list is cleared and filled again for each EloMask that you pass that list into.

To fix your issue, create a new list instead:

if (elo.ReadObjMask(i) > 0)
{
    var iRet = elo.PrepareObjectEx(0, 0, i);
    maskenname = elo.ObjMName();

    // create a new list here!!!
    var eigenschaften = new List<string>();

    if (maskenname != "")
    {
        for (int e = 0; e < 50; e++)
        {
            string eigenschaft = elo.GetObjAttribName(e);

            if (eigenschaft != "" && eigenschaft != "-")
            {
                eigenschaften.Add(eigenschaft);
            }
        }

        allMasks.Add(maskenname);

    }

    EloMask emask = new EloMask(maskenname, eigenschaften);
    staticVariables.allMask.Add(emask);

    // clearing the list is no longer needed                   
}
Comments