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!
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With