Tuesday, July 14, 2009

Structures and pointers in C#. How can I implement them?

Hi!


I want to implement the foloowing in C#:





struct mytree


{


char name[80]; // information


int noChildren; // number of children


mytree *children;


};





Is it possible? How?


Or can I do somethink like that, using C# types?


Please help!





I don't want to use pointers! (dangerous in C#)





Thanks!





PS: if you need more details, please try to imagine that


a run "tree" command from Dos Prompt (cmd.exe) and


a have to load all the folders in memory, in a structure.

Structures and pointers in C#. How can I implement them?
In C#, I would convert this to a class so that you could make use of the Generic List%26lt;T%26gt;.





class MyTreeNode


{


public string Name;


public List%26lt;MyTreeNode%26gt; MyChildren = new List%26lt;MyTreeNode%26gt;();


}





Here is an example of how its used:





class Program


{





static void Main(string[] args)


{


MyTreeNode node = new MyTreeNode();


MyTreeNode child = new MyTreeNode();


node.Name = "root";


child.Name = "child";


node.MyChildren.Add(child);


MyTreeNode childOfChild = new MyTreeNode();


childOfChild.Name = "childOfChild";


child.MyChildren.Add(childOfChild);





foreach (MyTreeNode nodeChild in node.MyChildren)


{


//access the children of root


foreach (MyTreeNode nodeGrandChild in nodeChild.MyChildren)


{


//access the children of each of root's children


}


}


Console.ReadLine();


}





This doesn't help you solve it using a C# struct, but it does get you out of using pointers.
Reply:I believe in C#, if you want to use pointers you will have to declare the struct as 'unsafe' as well. Example:





public unsafe struct mytree{ ....}





The thing about that is the fact the types, and properties declared within a piece of unsafe code will not be handled by the CLR.

salary survey

No comments:

Post a Comment