0

I've added a null property check to a boolean method, to prevent returning true, if any string fields are empty in a SelectedCustomer property.

The problem is my bool method gets called from the constructor, before I've input any data into the SelectedCustomer model. This then causes a Null reference exception.

I can see from the breakpoint I set on the statement that, "{"Object reference not set to an instance of an object."}" is the error. The selectedCustomer property isn't initialized until I select a customer from a data grid.

My question is, how can I perform the null check in this manner without causing a NRE?

This is the CanModifyCustomer boolean method where I perform the null check:

private bool CanModifyCustomer(object obj)
{

    if (SelectedCustomer.FirstName != null && SelectedCustomer.LastName != null && SelectedCustomer != null)
    {
        return true;
    }

    return false;            
}

It is passed as a param in my buttons command:

public MainViewModel(ICustomerDataService customerDataService) 
{
    this._customerDataService = customerDataService;
    QueryDataFromPersistence();

    UpdateCommand = new CustomCommand((c) => UpdateCustomerAsync(c).FireAndLogErrors(), CanModifyCustomer);

}

And this is the SelectedCustomer property that the null check is preformed on:

 private CustomerModel selectedCustomer;
    public CustomerModel SelectedCustomer
    {
        get
        {
            return selectedCustomer;
        }
        set
        {
            selectedCustomer = value;
            RaisePropertyChanged("SelectedCustomer");
        }
    }
Alexei Levenkov
  • 94,391
  • 12
  • 114
  • 159
Brian J
  • 5,416
  • 19
  • 94
  • 189
  • If the selectedCustomer property isn't initialized, then what do you think might be causing a **null** reference exception in your code? – Steve Nov 27 '15 at 00:28
  • Because the property wasn't initialized yet. It is initialized when I input values. But if I initialize it with default values my null check will never evaluate to true during program run. Or am I missing something silly here? – Brian J Nov 27 '15 at 00:36
  • What else could you check for null? – Steve Nov 27 '15 at 00:37

1 Answers1

2

Just use null conditional operator. (C#6)

if (SelectedCustomer?.FirstName != null && SelectedCustomer.LastName != null)
{
    return true;
}

Or you should put SelectedCustomer != null at first. because the condition is evaluated from left to right. so if first one is false because of using && operator it will not continue to check the other parts and the condition becomes false.

if (SelectedCustomer != null && SelectedCustomer.FirstName != null && SelectedCustomer.LastName != null)
{
    return true;
}
M.kazem Akhgary
  • 16,678
  • 6
  • 49
  • 100
  • ok that resolved the issue, thanks. I just had to check if the property itself was null also in summary not just the fields. – Brian J Nov 27 '15 at 00:48