0

Please, help me with this problem:

I Try define a structure like this:

 unsafe struct sNodo<T>
{    
        public T info;
        public sNodo<T>* sIzq;}

but i get this error: Cannot take the address of, get the size of, or declare a pointer to a managed type sNodo,

how can I fix it? I'm trying to create a stack "generic" using dynamic memory.

Thank you for your attention

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
Carlos B
  • 1
  • 1
  • 1
  • "Because i need use pointers (dinamic memory)."... er - why? That isn't enough to explain what you are trying to do. – Marc Gravell Oct 17 '09 at 07:47

1 Answers1

9

If all you need is to create a generic stack, you don't need unsafe. Just use the normal C# language:

class StackNode<T> {
    public T info;
    public StackNode<T> next;
}

Why exactly do you feel you need unsafe?

Maybe you're thinking that you need a pointer because the otherwise your type can't have another instance of the same type as a data member. Indeed, in C# if you try to do:

struct Foo {
    int data;
    Foo next;
}

...the C# compiler will complain about circular struct references and refuse to compile your code (if you don't see why it has to do that, try to figure out how many bytes a Foo object should take up in memory).

But if you try to do the same thing with the class keyword:

class Bar {
    int data;
    Bar next;
}

...everything works! If you come from a C++ background, where classes and structs are more or less the same thing, this is very puzzling.

The secret is that in C#, structs have value semantics while classes have reference semantics. So the C++, the above two definitions are most similar to:

class Foo {
    int data;
    Foo next; // This doesn't compile in C++ either.
}

class Bar {
    int data;
    Bar* next; // But this is ok.
}

This C++ code isn't completely equivalent, of course, but it should give you a basic idea of what to expect.

Bottom line: if you're just learning C#, don't use structs; everything they can do, classes can do too. Once you understand C# semantics, and are sure that the value semantics structs give you can provide you with a performance benefit, and are sure that that performance benefit actually matters to your app, go ahead and use them.

David Seiler
  • 9,557
  • 2
  • 31
  • 39