imdrunkisuppose
imdrunkisuppose

Reputation: 131

C# How to find a Class' non created objects?

I have this class

class Node
{
    public bool is_end;
    public int prefix_count;
    public Node[] child = new Node[26];
}

My problem is, the class only creates Nodes if it is necessary, but later in the program, i need to check all the created Nodes, though since i don't know which ones are created, i can't use a cycle for it.

Is there a way for me to know which Nodes are created, is there a code to check if this Node exists or not.

Upvotes: 2

Views: 92

Answers (3)

Reed Copsey
Reed Copsey

Reputation: 564433

In this case, your child array is pre-created, but each individual node is not allocated. You can check for null to see if a Node has been created:

bool ChildCreated(Node parent, int childIndex)
{
    return parent.child[childIndex] != null;
}

I have to find out which child nodes are created, for example a cycle from 0 to 25, and it has to give a message like node[2] and node[11] are created, others aren't.

Using this method, you could easily do:

var created = Enumerable.Range(0, node.child.Length).Where(i => ChildCreated(node, i)).ToList();
if (!created.Any())
{
    Console.WriteLine("No children created.");
}
else
{
    Console.WriteLine("Children {0} created, all others aren't.", string.Join(", ", created));
}

Upvotes: 3

Brad M
Brad M

Reputation: 7898

Try using a List<Node> instead of a fixed length array. Then you can use methods such as

var nodeList = new List<Node>();
nodeList.Add(someRandomNode);
if (nodeList.Contains(someRandomNode)) 
{
    // your logic
}

You may also iterate over your Node collection.

foreach(var node in nodeList) { }

Upvotes: 4

Zbigniew
Zbigniew

Reputation: 27594

All you need to do is to check if Node[] element is null:

int nodeIndex = 0;
if(child[nodeIndex] == null)
{
    // node doesn't exist
}
else
{
    // node exists
}

Upvotes: 1

Related Questions