unsafe public class Temp
{
public struct Node
{
Node *left;
Node *right;
int value;
}
public Temp()
{
Node* T=new Node();
T->left=null;
T->right=null;
T->value=10;
}
}
main()
{
Temp temp=new Temp();
}
It gives error that Object reference not set to instance of an object. How can I do it when I want to make AVL Tree Program(which I have created and tested in C++ but copying in C# gives error)
Don't try to use pointers in C# like this. If you are porting C++ code that uses pointers as references, instead use reference types. Your code will not work at all; "new" does not allocate structs off the heap, for one thing, and even if it did pointers are required to be pinned in place in C#; C# is a garbage-collected language.
In short never use unsafe
unless you thoroughly understand everything there is to know about memory management in C#. You are turning off the safety system that is there to protect you, and so you have to know what that safety system does.
The code should be:
public class Temp // safe, not unsafe
{
public class Node // class, not struct
{
public Node Left { get; set; } // properties, not fields
public Node Right { get; set; }
public int Value { get; set; }
}
public Temp()
{
Node node = new Node();
node.Left = null; // member access dots, not pointer-access arrows
node.Right = null;
node.Value = 10;
}
}
The problem is with the line:
Node* T=new Node();
In C#, new Node()
returns Node
(which is reference), not Node*
(which is pointer).
You should use stackalloc, instead.
Anyway, please do not copy C++ and do it C# way!
You cannot assign a .NET variable to a pointer you can only take it's address. If you do not reference a new
ed Node
it gets garbage collected immediately, therefore you've probably ran into "object reference not set". Expression like Node* T = new Node()
should not compile however, since it effectively tries to do an invalid type conversion.
What you are trying to do is wrong: do not copy and paste C++ code to C#, this is nonsense. If you already got tested C++ components use .NET/unmanaged interop to marshal data between the two worlds, though I would not recommend to do it at this level of abstraction. If you're doing an exercise, implement an AVL tree in .NET world only, otherwise use one of the framework collections with equivalent functionality e.g. SortedSet
or SortedDictionary
...