Ali Moosavi
Ali Moosavi

Reputation: 179

can't change objects that are in a strongly-typed generic list

I am trying to iterate over all objects in a List with array subscription operator and change a field in them, and then store a reference of them in another list. Here is the code I have written:

private List<JavaScriptEventM> getSubset(List<JavaScriptEventM> domEvents)
    {
        List<JavaScriptEventM> retVal = new List<JavaScriptEventM>();

        for (int i = 0; i < domEvents.Count; i++)
        {
            JavaScriptEventM e = domEvents[i];
            e.xpath = getXPathToNode(e.source , false);
            retVal.Add(e);
        }

        return retVal;
    }

This code is supposed to access all members of a list called domEvents and change their xpath public field and store the reference also in another list (called retVal)

I call this function and pass a List of JavaScriptEventM objects that have their xpath field set to null. Strangely, after the function returns, the objects returned in retVal have their xpath field changed, but the original domEvents list passed as parameter to this function remains untouched. i.e the objects in the original list still have their xpath field set to null.

Is it that C# actually gets a clone of the object when you access it through array subscription operator on a List? How can I access all elements of a List one by one and change them?

Upvotes: 0

Views: 156

Answers (1)

Alexei Levenkov
Alexei Levenkov

Reputation: 100620

Do not use struct in C# unless you know exactly what it is doing. I.e. struct's value semantics leads to problem like your one where original data does not get changed.

Unlike C++ there is a huge difference between struct and class in C#.

Classes and Structs

What's the difference between struct and class in .NET?.

Upvotes: 3

Related Questions