We seem to be getting all the information when the ID matches, but
when there is no matching ID the program just crashes and gives us the
following error.
That makes perfect sense. Given your code, if there is no match for the given Employee
by his Id
, you return null
. Hence, if you do this:
var employee = SearchForEmployee(1);
// Attempting to access the Id propery on a null value will throw.
Console.WriteLine(employee.Id);
Then that will through a NRE, because the return value was null
. You need to add a null check to your code:
var employee = SearchForEmployee(1);
if (employee != null)
Console.WriteLine(employee.Id);
Or, you can use C#-6 null conditional operator:
var employee = SearchForEmployee(1);
Console.WriteLine(employee?.Id);
Side note - Your null
check inside SearchForEmployee
is redundant, as you return null
anyway if there's no match. This will do:
private Employee SearchForEmployee(int Id)
{
return (from emp in EmployeeArray
where emp.m_EmployeeId == Id
select emp).FirstOrDefault();
}
Or again, using C#-6:
private Employee SearchForEmployee(int Id) =>
EmployeeArray.FirstOrDefault(emp => emp.m_EmployeeId == Id);
Edit:
From the comments:
Looks like this: private Employee[] EmployeeArray = new Employee[50];
It is created when the windows form loads up, and it is only
initialized when an employee is registered. We are using this method
after atleast one employee was added.
Well, your only initializing the array, but not the references that are stored inside that array. This means that you may have a single Employee
object initialized there, but you have another 49 which aren't.
You have two options, either modify your query to include a null
check:
private Employee SearchForEmployee(int Id)
{
return EmployeeArray.FirstOrDefault(emp => emp != null && emp.m_EmployeeId == Id);
}
Or you could use a List<Employee>
instead, which means that it would only contain the employees you already added, and it will dynamically resize as you add more employees to it, with no extra work from your end.