tags:

views:

192

answers:

1

Hi

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

+5  A: 

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
Ageed. I think the OP just misunderstands the usage of value types and reference types (structs and classes here).
Noldorin
Or you could just use Stack<T> and not reinvent the wheel :)
Ryan Emerle
Because i need use pointers (dinamic memory).
Carlos B
Why do you feel that you need to use pointers? And what does "dynamic memory" mean?
Eric Lippert