Reputation: 17186
The following code is designed so that if I change the array assigned to one node it will not affect the other node.
My question is: Is there a more "idiomatic" way to accomplish this?
void Main()
{
var arr = new [] { 1, 2, 3 };
var node1 = new Node();
node1.Children = arr;
var node2 = new Node();
node2.Children = arr;
node1.Children[0] = 9; // node2 SHOULD NOT be affected by this
node1.Dump();
node2.Dump();
}
class Node
{
private int[] children;
public int[] Children
{
get { return children; }
set
{
children = new int[value.Length];
value.CopyTo(children, 0);
}
}
}
Upvotes: 0
Views: 82
Reputation: 32481
What about this [EDITED]:
class Node
{
private int[] _children;
public Node(int[] children)
{
this._children = (int[])children.Clone();//HERE IS THE IDEA YOU ARE LOOKING FOR
}
public int this[int index]
{
get { return this._children[index]; }
set { this._children[index] = value; }
}
}
Upvotes: 3
Reputation: 13077
I think you would be better off changing the array object copy semantics rather than adding features to the Node class to support this. Fortunately there is already a class with the semantics you are looking for: List.
This simplifies the Node class:
class Node
{
public List<int> Children { get; set; }
}
The result:
static void Main(string[] args)
{
var arr = new[] { 1, 2, 3 };
var node1 = new Node
{
Children = new List<int>(arr)
};
var node2 = new Node
{
Children = new List<int>(node1.Children)
};
node1.Children[0] = 9; // node2 SHOULD NOT be affected by this
Console.WriteLine("First element node1:{0}, first element node2:{1}",
node1.Children[0], node2.Children[0]);
}
Upvotes: 0