-3

I use a function that save string into a string array but visual 2012 show this error Object reference not set to an instance of an object.

this is my code :

 public void ShowLinkList(ref TreeNode t, ref string[] Data, ref int i)
   {
       string str;
       if (t!= null)
       {
           ShowLinkList(ref t.LeftChild, ref Data, ref i);
           Data[i] = CreatStr(t.Parent.Word) + "," + CreatStr(t.LeftChild.Word )+ "," + CreatStr(t.RightChild.Word) + "," + CreatStr(t.Word);
           i++;
           ShowLinkList(ref t.RightChild, ref Data, ref i);
       }
   }
   public string CreatStr(string str)
   {
       if (str == "")
       {
           return "__";
       }
       return str;
   }

when t is null,the "if(t != null)" not allowed compiler to debug ,the CreatStr(string) convert a null string to "__" in output(windows form C#) this metode (ShowLinkList) saving t.parent.word & t.leftchild.word & t.rightchild.word & t.word in a string array please help me.thank you

Programmer
  • 23
  • 1
  • 6

1 Answers1

0

First, "" is equal to string.Empty and not equal to null

You have no error handling for any of the properties of t so if any of these are null then it won't have a clue what Word is, I'd suggest at the very least creating the following method on TreeNode

public bool HasValidBranches()
{
    return Parent != null && LeftChild != null && RightChild != null;
}

then add this to your error handling that is already present and feel free to modify to suit your needs

if(t != null && t.HasValidBranches())
....

Note: You could always just add the extra null checks directly to the current code.

Sayse
  • 42,633
  • 14
  • 77
  • 146
  • I try to use this ..but not debug!!! – Programmer May 29 '14 at 06:54
  • I try to save parent and rightchild and leftchild of a word in a text file – Programmer May 29 '14 at 07:00
  • and maybe compiler not allowed to saving a null value to a string array,because maybe a parent node is null and i try change null to "-" to print at output – Programmer May 29 '14 at 07:03
  • This has nothing to do with trying to save a null value to a string array, you can't concatenate a string to null, and plus I don't think it even gets that far, `Word` is not a property of `null` – Sayse May 29 '14 at 07:04