LINQ to XML Cloning

Posted by Sir Psycho on Stack Overflow See other posts from Stack Overflow or by Sir Psycho
Published on 2010-04-13T13:04:38Z Indexed on 2010/04/13 13:13 UTC
Read the original article Hit count: 445

Filed under:
|

Can anyone explain why the original address XElement street node changes? It looks like customer1 holds a reference to the address XElement but customer2 and customer3 have taken copies.

Why did the original address change? (LINQPad example)

var address =
    new XElement ("address",
        new XElement ("street", "Lawley St"), 
        new XElement ("town", "North Beach")
    );

var customer1 = new XElement ("customer1", address);
var customer2 = new XElement ("customer2", address);
var customer3 = new XElement ("customer3", address);

customer1.Element ("address").Element ("street").Value = "Another St";

Console.WriteLine (customer2.Element ("address").Element ("street").Value);
Console.WriteLine ();

address.Dump();
Console.WriteLine ();

customer1.Dump();
Console.WriteLine ();

customer2.Dump();
Console.WriteLine ();

customer3.Dump();

OUTPUT

Lawley St


<address>
  <street>Another St</street>
  <town>North Beach</town>
</address> 


<customer1>
  <address>
    <street>Another St</street>
    <town>North Beach</town>
  </address>
</customer1> 


<customer2>
  <address>
    <street>Lawley St</street>
    <town>North Beach</town>
  </address>
</customer2> 


<customer3>
  <address>
    <street>Lawley St</street>
    <town>North Beach</town>
  </address>
</customer3> 

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about c#