0

I wrote a spike solution for a basic tree building class that I created.

The Output for the first "Adding Item No {0} at the depth of {0}" is item 0 depth 0, not the expected 0,1.

It just hit me as I was writing this out. Could it be due to my down casting, even though I set aside enough memory at the start?

C# Code:

static void Main(string[] args)
{
    object HeadNode = 0;

    Console.WriteLine("Creating Head Node Filling Tree");
    HeadNode = new Node(0, 1,  HeadNode);
    ((Node)HeadNode).AddNode( HeadNode);
    ((Node)HeadNode).CountChildNodes();

    Console.ReadKey();
}

public struct Node
{
    List<Node> nodes;

    int nCount;
    int nDepth;
    int nNoChildren;
    object headNode;

    public Node(int count, int depth,  object head)
    {
        nodes = new List<Node>();
        nNoChildren = 0;
        nDepth = depth;
        nCount = count;
        headNode = head;
    }

    public int AddNode( object head)
    {
        while (nCount < 2 && nDepth < 3)
        {
            Console.WriteLine("Adding node to this object {0}", GetHashCode());
            Console.WriteLine("Adding Item No {0} at the depth of {0}", nCount, nDepth);
            nodes.Add(new Node(nodes.Count(), nDepth + 1,  headNode));
            nCount += 1;
            nodes[nodes.Count() - 1].AddNode(headNode);

        }
        return -1;
    }
abatishchev
  • 98,240
  • 88
  • 296
  • 433

1 Answers1

1

"The Output for the first "Adding Item No {0} at the depth of {0}" is item 0 depth 0, not the expected 0,1."

You're printing the same value twice ({0} at two different places), how it expected to print two different values (0 and 1).

I guess you want this instead :

Console.WriteLine("Adding Item No {0} at the depth of {1}", nCount, nDepth);

{0} will be replaced with value from the 2nd parameter (nCount) and {1} will be replaced with value from the 3rd parameter (nDepth).

har07
  • 88,338
  • 12
  • 84
  • 137
  • `Console.WriteLine("Adding Item No {0} at the depth of {1}", nCount, nDepth);` {0}tells WriteLine where and what format to sub in the objects that follow. – Omicrom Mar 12 '14 at 01:57
  • Hmm.. I don't get the point from your comment. So, does changing the 2nd `{0}` to `{1}` fix the problem? – har07 Mar 12 '14 at 05:44