0

I'm trying to write a function where it will have two list:

  1. original list (fooList)
  2. list that contains extra info (fooWithExtList)

But not sure why when I concat the text in another list, it also update the information in my original list.

Here's the code:

    var fooDataList = new List<Foo>();
    fooDataList.Add(new Foo { Bar = "Test1" });
    fooDataList.Add(new Foo { Bar = "Test2" });
    fooDataList.Add(new Foo { Bar = "Test3" });
    fooDataList.Add(new Foo { Bar = "Test4" });

    var fooList = new List<Foo>();
    var fooWithExtList = new List<Foo>();

    //assign foodata to fooList
    fooDataList.ForEach(fdl => fooList.Add(fdl));

    //assign foodata to fooWithExtList
    fooDataList.ForEach(fdl => fooWithExtList.Add(fdl));

    //set the fooWithExtList with extra info
    fooWithExtList.ForEach(fwel => fwel.Bar = fwel.Bar + "ext");

    //merge the list
    fooList = fooList.Concat(fooWithExtList).ToList();

Result:

Test1ext Test2ext Test3ext Test4ext Test1ext Test2ext Test3ext Test4ext

Expecting:

Test1 Test2 Test3 Test4 Test1ext Test2ext Test3ext Test4ext

dot net fiddle here: https://dotnetfiddle.net/0nMTmX

Milo Khoo
  • 53
  • 2
  • 11
  • You are using the same _reference_ and thus you get the three lists pointing all to the same data. Need to understand the difference between reference and value types. – Steve Apr 06 '17 at 18:02
  • Something like [C# Concepts: Value vs Reference Types](http://www.albahari.com/valuevsreftypes.aspx) – Steve Apr 06 '17 at 18:05

1 Answers1

1

You need to create different instances of the Foo class that you add to the first list if you want them to exists as separate entities. Otherwise you add the reference to the same instance in your three lists and thus, the change made to one of the Foo instances is reflected by the three lists.

A possible solution. Suppose that your Foo class has a Copy method....

public class Foo
{
    public string Bar {get;set;}
    public Foo(string bar)
    {
        Bar = bar;
    }
    public Foo Copy()
    {
        Foo aCopy = new Foo(this.Bar);
        return aCopy;
    }
}

Now you can write

//assign copies of foodata to fooList
fooDataList.ForEach(fdl => fooList.Add(fdl.Copy()));

As pointed in the comment above, good readings are
C# Concepts: Value vs Reference Types
MSDN documentation
Or on this same site from Jon Skeet

Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286