4

Given the code:

from i in this.GridViewFoo.SelectedItems
select new EmployeeEntity
{
    EmployeeID = (i as EmployeeDto).EmployeeID,
    Email = this.GetAllEmail((i as EmployeeDto).Email, (i as EmployeeDto).SecondaryEmails),
    EmployeeNumber = (i as EmployeeDto).EmployeeNumber,
    FirstName = (i as EmployeeDto).FirstName,
    LastName = (i as EmployeeDto).LastName
}

After the safe cast (i as EmployeeDto) may I receive a NullReferenceException. How can I ensure and safety of the code and not overload him with a lot of null checks?

Overview of solutions:

I did some tests to assert if the solutions are working. Both are working well and bring the same result, you can check HERE. After that I did some performance tests with OfTypeSolution and letSolution.

As OfType solution have better times in average, this will be the answer!

Custodio
  • 8,594
  • 15
  • 80
  • 115
  • Possible duplicate of [When to use Cast() and Oftype() in Linq](http://stackoverflow.com/questions/4015930/when-to-use-cast-and-oftype-in-linq) – Michael Freidgeim Aug 25 '16 at 08:05

2 Answers2

11

You can use OfType before the Select:

from i in this.GridViewFoo.SelectedItems.OfType<EmployeeDto>()
select new EmployeeEntity
{
    EmployeeID = i.EmployeeID,
    Email = this.GetAllEmail(i.Email, i.SecondaryEmails),
    EmployeeNumber = i.EmployeeNumber,
    FirstName = i.FirstName,
    LastName = i.LastName
}

it will provide you only with the EmployeeDto type items from the SelectedItems so there is no need to cast and null checking.

nemesv
  • 138,284
  • 16
  • 416
  • 359
2
from si in this.GridViewFoo.SelectedItems
let i = si as EmployeeDto
where i != null
select new EmployeeEntity
{
    EmployeeID = i.EmployeeID,
    Email = this.GetAllEmail(i.Email, i.SecondaryEmails),
    EmployeeNumber = i.EmployeeNumber,
    FirstName = i.FirstName,
    LastName = i.LastName
}
Wasp
  • 3,395
  • 19
  • 37