Ryan Peschel
Ryan Peschel

Reputation: 11828

Why does this code initialize an object and then make another object equal to it?

Here's the function:

private static void AddToTree(TreeNode target, DataRow dataRow)
{
    var node2 = new TreeNode(dataRow["name"].ToString())
    {
        ImageIndex = target.ImageIndex,
        SelectedImageIndex = target.SelectedImageIndex,
        Tag = dataRow
    };
    TreeNode node = node2;
    target.Nodes.Add(node);
}

I see similar code throughout the codebase. Why not just add node2 to the target nodes and not create another variable? Am I missing something?

Upvotes: 2

Views: 72

Answers (2)

Nicolas Voron
Nicolas Voron

Reputation: 3006

You're not missing anything. This code is redudant.

TreeNode node = node2; //<--- Assign the object reference of node2 to node. 
                       //     There is no object copy or wathever.

Upvotes: 3

Aghilas Yakoub
Aghilas Yakoub

Reputation: 29000

I'think that you can replace

target.Nodes.Add(node2);

You can take copy of reference, but in order to compare in second time with result query or another treatment, but with just this code, you can replace

Upvotes: 0

Related Questions