C# does not like pointers, but I need to use them now to create a linked list, like we would do in C. The struct is simple:
public unsafe struct Livro
{
public string name;
public Livro* next;
}
But I get the error: "Cannot take the address of, get the size of, or declare a pointer to a managed type". Any ideas?
The problem is the string declaration. You have to go low level and use char* pointers. Using
unsafe
comes with all the headaches of leaving the managed world...Use a class instead of a struct and then the pointer becomes a reference:
And then it would be a good idea to use properties instead of public fields.
you can do it with struct like this:
or like this:
but it's better to just use
class
for the linked list instead.You can just use a
class
instead of astruct
:This will provide the proper behavior automatically.
That being said, you might want to just use the
LinkedList<T>
class from the framework directly.