struct with creates cycle

  • Thread starter Thread starter Morten Nielsen
  • Start date Start date
M

Morten Nielsen

I'm trying to convert the following struct from C to C#, but have a problem
with the two pointers that point back to the same structure.

struct BSP_Node {
byte axis;
float plane;
BSP_Node *left; // ARGH!
BSP_Node *right; // ARGH!
bool leaf;
Object *objects;
};

First I tried creating a structure like the one below, but the compiler
complains about the cycle that 'left' and 'right' creates.
public struct BSP_Node
{
public byte axis;
public float plane;
public BSP_Node left;
public BSP_Node right;
public bool leaf;
public object objects;
}

Does anyone know how to translate this structure correctly ? The ref keywork
can't be used either, so that I could make 'left' and 'right' work like
pointers.

Regards
/Morten Nielsen
 
In C structs can be created on the heap, just like classes, which is why
the pointers make sense.
In C# structs can only be created on the stack, so the compiler is
trying to create a BSP_Node that actually *contains* two BSP_Nodes...
You need to change the struct to a class.
 
Uri Dor said:
In C structs can be created on the heap, just like classes, which is why
the pointers make sense.
In C# structs can only be created on the stack, so the compiler is
trying to create a BSP_Node that actually *contains* two BSP_Nodes...
You need to change the struct to a class.

While I agree that the solution is to change it to a class, it's not
true that structs are only created on the stack.

See http://www.pobox.com/~skeet/csharp/memory.html
 
Back
Top