System.NullReferenceException was unhandled by user code RRS feed

  • Question

  • Hi

    I am getting "System.NullReferenceException was unhandled by user code" on below code;

    tbl.Rows.Add(New Object() {"", 0, IIf(IsNothing(x.Unit), "", x.Unit.Unit), ""})

    x.Unit is Nothing but shouldn't IIF take care of it?

    I have also tried;

    tbl.Rows.Add(New Object() {"", 0, IIf(x.Unit Is Nothing, "", x.Unit.Unit), ""})

    Still no luck. What am I missing?



    Thursday, March 26, 2015 9:11 PM


  • IIf is a function. Before a function is called, all arguments are being computed. This includes x.Unit.Unit. Hence the exception. IIf is old, but the If() expression has been introduced.

    IsNothing is also old. Instead of calling a function that checks if a reference is Nothing, directly check if it's Nothing.

    Try this:

    tbl.Rows.Add(New Object() {"", 0, If(x.Unit Is Nothing, "", x.Unit.Unit), ""})


    • Edited by Armin Zingler Thursday, March 26, 2015 9:32 PM
    • Proposed as answer by .paul. _ Thursday, March 26, 2015 9:45 PM
    • Marked as answer by Y a h y a Thursday, March 26, 2015 9:50 PM
    Thursday, March 26, 2015 9:31 PM