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.