0

Currently have a list that you are able to add customer details to through user input. later in the software I then use linq to search the list in order to find if the customer details already exist in the list. I currently have an if statement (listed below) that takes the return value from linq and displays if the customer has details already stored on the list.

    Customer cust = finder.list.where(c => c.ID.ToString() == textBox.txt).FirstOrDefault();

    if(cust.ID == null)
    {
        lstDisplay.items.add("Customer details not stored")
    }

The issue I am having is that the program crashes once it reaches the if statement with the error: 'Object reference not set to an instance of an object.'

train was null.

how to I handle null being returned.

If null is returned to the value train.ID I want to compare it to null like I have in the if statement. If it is null then I want to be able to display the message box Like I have done

  • 2
    Your trying to see if cust.ID is null, you need to check if the entire CUST object is null – Brad Nov 12 '18 at 17:23
  • Simple solution: check if `cust` is null – CodeLikeBeaker Nov 12 '18 at 17:23
  • Is linq aware that the ID field in the customer table is nullable? i.e. "int?" (question mark intended) – Phill Nov 12 '18 at 17:27
  • That's not valid Linq...`Where` is capitalized. – Rufus L Nov 12 '18 at 17:47
  • Also in your `Where` condition, if `ID == null`, then this will fail before you ever get to the `if` statement: `c.ID.ToString()`. So you should change that part as well: `.Where(c => c.ID?.ToString() == textBox.txt)` – Rufus L Nov 12 '18 at 17:49

1 Answers1

1

You need to check if cust is null

if(cust?.ID == null)
{
    lstDisplay.items.Add("Customer details not stored")
}
JuanR
  • 7,405
  • 1
  • 19
  • 30
Sean T
  • 2,414
  • 2
  • 17
  • 23