0
private Employee searchForEmployee(int ID)
{
    var EmployeeDetails = (from emp in EmployeeArray
                           where emp.m_EmployeeId == ID
                           select emp).FirstOrDefault();
    if (EmployeeDetails != null)
    {
        return EmployeeDetails;
    }
    else
    {
        return null;
    }
}

The issue(sorry for the bad format, Im new to this and to Linq):

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:

Additional information: Object reference not set to an instance of an object. If there is a handler for this exception, the program may be safely continued.

Please help!

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Oz Franko
  • 13
  • 2
  • 2
    maybe, because you return `null`? – Backs Sep 28 '15 at 14:41
  • How are you using the return value from this method? – Yuval Itzchakov Sep 28 '15 at 14:42
  • There's 'nothing wrong' (nothing that would raise an exception) with this code. If something calls `searchForEmployee` and attempts to reference a property of the `null` that's returned - you'll get this exception. –  Sep 28 '15 at 14:43
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – TomDoesCode Sep 28 '15 at 14:46
  • 1
    with your current code there is zero point in doing your null check since you are only returning a null in the else anyways. – user1666620 Sep 28 '15 at 14:49

2 Answers2

1

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.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • Hey, thanks for responding so fast. Where exactly should I put this? It keeps crashing the moment it gets to the "where" section. Am I supposed to run a null check before it? If so, how should it be written? edit: Just refreshed and I see you wrote some more stuff, Ill look into it. – Oz Franko Sep 28 '15 at 14:54
  • @OzFranko If it crashes in your `where` clause, then your array is probably not initialized. How do you instansiate the `EmployeeArray`? – Yuval Itzchakov Sep 28 '15 at 14:55
  • 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. – Oz Franko Sep 28 '15 at 14:59
  • Yuval, toda raba al hacol ya meleh! I actually needed to use Lambdas in this project, so your answer was more than perfect. Honestly I am still struggling abit to get the grasp of how they work, but I will go over your code a couple of times and hopefully Ill learn to use it like that. Perfect! Thank you for everything, you're awesome! – Oz Franko Sep 28 '15 at 15:13
  • @OzFranko They're not that difficult. Start [here](https://msdn.microsoft.com/en-us/library/bb397687.aspx), and read read read. – Yuval Itzchakov Sep 28 '15 at 15:15
0

The method you posted is not throwing the error. Somewhere in your code you are invoking the method, which is returning null. You are then trying to access one of it's property, and since the object is null you get that error. For example you probably have something like this:

Employee emp = searchForEmployee(18);
string name = emp.Name; //This will throw an error if no employee exists with id of 18

As a result you need to check if emp is not null first as such:

if(emp != null)
{
    string name = emp.Name;
}

Of course I'm just guessing if name is a property but you should get the point. What you could also do is change the method so it returns a default employee object if you rather not return null. Something like this:

private Employee searchForEmployee(int ID)
{
    var EmployeeDetails = (from emp in EmployeeArray
                           where emp.m_EmployeeId == ID
                           select emp).FirstOrDefault();
    if (EmployeeDetails != null)
    {
        return EmployeeDetails;
    }
    else
    {
        return new Employee
        {
            ID = 0,
            Name = "default", //etc
        };
    }
}
John Paul
  • 827
  • 2
  • 6
  • 16