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");
}
}