-1

As shown below I have a method in my class that returns null as expected when it does not successfully read a value. I assume that the object "test" would just be set to NULL but for some reason an error is getting thrown.

enter image description here

I don't understand why this would throw an error...

private string myNullFunction() { return null; }
private void myFunction()
{
  object test = myNullFunction();
}

when this does not...

private void myFunction()
{
  object test = null;
}
Arvo Bowen
  • 4,524
  • 6
  • 51
  • 109
  • 3
    What do you think `null.Value` would do? – Matt Burland May 27 '16 at 17:04
  • probably `m_xml` or `m_xml.Read(...)` is `null` – Arturo Menchaca May 27 '16 at 17:04
  • @MattBurland In response to your flag... That other question is VERY broad. Looking at that question I would have never realized what my actual problem was. Only when you said "null.Value" did I realize the null was coming from Read() and not .Value. – Arvo Bowen May 27 '16 at 17:11
  • Your question is very broad and exact like the first example in the answer to the dupe: `ref1.ref2.ref3.member` And the answer is exactly the same. You have to make sure every step of your chain is not null. Every time you use a `.` you have to consider if the thing you are putting that `.` on is null. – Matt Burland May 27 '16 at 17:13

2 Answers2

2

Read function is returning null. That's why null reference exception is there.

Akshey Bhat
  • 8,227
  • 1
  • 20
  • 20
  • I was just about to tell Matt to put that in an answer! ;) That was exactly what the problem was... I just was not thinking it through. I wish the IDE would say something like that... "The Read() method is null" or something. – Arvo Bowen May 27 '16 at 17:07
2

Your sample code does not actually throw an exception. The real issue is shown in the code snippet above the exception dialog: m_xml.Read is returning null, but you are trying to access the Value property.

competent_tech
  • 44,465
  • 11
  • 90
  • 113