-1

I have following classes.

class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
}

class Bonus
{
    public int EmployeeId { get; set; }
    public int Amount { get; set; }
}

class EmployeeBonus
{
    public int ID { get; set; }
    public string Name { get; set; }
    public int Amount { get; set; }
}

I need to do a left join so that if en EmployeeId does not exists in the Bonus class, the Amount should be zero. Here is how its implemented

class Program
{
    static void Main(string[] args)
    {
        List<Employee> employees = new List<Employee>()
        {
            new Employee() { ID = 1, Name = "John" },
            new Employee() { ID = 2, Name = "Doe" },
            new Employee() { ID = 3, Name = "Charles" },
            new Employee() { ID = 4, Name = "Mike"},
        };

        List<Bonus> bonus = new List<Bonus>()
        {
            new Bonus() { EmployeeId = 1, Amount = 10 },
            new Bonus() { EmployeeId = 2, Amount = 3 },
        };
        try
        {
            var result = (from e in employees
                          join b in bonus on e.ID equals b.EmployeeId into ps
                          from b in ps.DefaultIfEmpty()
                          select new EmployeeBonus()
                          {
                              ID = e.ID,
                              Name = e.Name,
                              Amount = b.Amount == 0 ? 0 : b.Amount
                          }).ToList();
        }
        catch(Exception ex)
        {

        }
    }
}

However I get following exception in the code above.

{"Object reference not set to an instance of an object."}

at ConsoleApplication2.Program.<>c.b__0_4(<>f__AnonymousType02 <>h__TransparentIdentifier0, Bonus b) in c:\users\john\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 31 at System.Linq.Enumerable.<SelectManyIterator>d__223.MoveNext() at System.Collections.Generic.List1..ctor(IEnumerable1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at ConsoleApplication2.Program.Main(String[] args) in c:\users\john\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 28

What's the best way of addressing this issue?

jim crown
  • 473
  • 3
  • 11

1 Answers1

1

In this case, b (of type Bonus) is null. So accessing b.Amount is illegal.

Check b for null before use.

Amount = b != null ? b.Amount : 0

Or C# 6 (although I prefer the former):

Amount = b?.Amount ?? 0;

An int cannot be null.

user2864740
  • 60,010
  • 15
  • 145
  • 220