Search code examples
c#generic-handler

Error returning null from generic type object C#


I am having issue returning null from generic type object in BSTree

This Is the Error : A first chance exception of type 'System.NullReferenceException' occurred in System.exe Additional information: Object reference not set to an instance of an object. If there is a handler for this exception, the program may be safely continued

and my code it

        public BTree()  //creates an empty tree
    {
        root.Name = default(T);
        root.Members = default(T);
    }

Thanks

I set root to be :

public BST()
    {
        root = null;
    }

Solution

  • The problem here is that root is currently null and you're getting an exception trying to set it's members. Given that BTree() is a constructor and root a presumably instance field, you need to initialize it before use

    public BTree() {
      root = new Artist<T>();
      root.Name = default(T);
      root.Members = default(T);
    }
    

    EDIT

    Updated based on PasteBin code