az**********@gmail.com wrote:
Thanks a lot for answering it.
Im coming from C, and I am trying to convert some codes to C# just 4
fun. Since there are many structs pointing to each other and to
theriselves, I was wondering how could I do it in C#. That's why I was
coding this stack.
Well, just as that's not a great way to implement a stack in C#, it
wouldn't really be a great way to implement it in C.
But the more general issue here is that you've got a data type that you
expect to be stored as a reference on a regular basis, making it more
appropriate as a reference type than a value type.
It's very important, if you're going to know C#, to understand the
difference between reference types and value types. They look very
similar in the language, but have very specific, different behaviors.
Generally speaking, classes are reference types, while structs and
primitive types are value types.
So, Should I do it using classes only? You said something about
allowing the struct to be boxed. How can I do it, so that I can use an
object type to refer the struct?
The language does it automatically. If you assign a value type to a
variable that's of type object, or pass it as a parameter of type
object, etc. the compiler will generate code that creates an object
instance that contains the value type you've used.
If you later assign that object back to a value type, the compiler will
again generate the code necessary to get the value type data out of the
object instance and copy it to the value type instance.
One thing to keep in mind here is that when the value type is boxed, you
get a whole new instance. If you box the same value instance multiple
times, you get multiple instances, each with a new copy of the value type.
Again, if you need to reference a specific instance of a piece of data,
you really should be using a reference type.
What about using this System.IntPtr type?? I don't know what it does,
but maybe it can help me
Probably not. It is sort of like a "void *", but the issue here is that
you don't have a type that is easily referenced, because it's a value
type. Value types are meant to be passed around intact, not referenced.
You can do thing that will cause them to be referenced, but IMHO it is
better to just use a reference type in the first place, if you want to
be able to reference the data.
Pete