-2

I know why this is occuring, I am looking for a property in my Model that may or may not be there, if it's there it generates some HTML, if it isn't it generates different HTML so I am having to wrap it in a try catch (which is in the middle of a foreach:

@try
{
    if (item.tbl_computerinfo.FirstOrDefault().teamviewerID != null)
    {
        <td class="text-center"><a href="javascript:TeamviewerConnect(@Html.DisplayFor(modelItem => item.tbl_computerinfo.FirstOrDefault().teamviewerID)"><img src="~/Content/images/icons/teamviewericon.png" alt='TeamviewerID' border='0' title='@Html.DisplayFor(modelItem => item.tbl_computerinfo.FirstOrDefault().teamviewerID)'></a></td>
    }
}
catch (Exception)
{
    <td></td>
}

Subsequently this generates hundreds of:

Exception thrown: 'System.NullReferenceException' in System.Web.Mvc.dll

in the output. This is slowing down the page significantly. Is there a better way to deal with the null reference exception that doesn't slow down the page?

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
Trinitrotoluene
  • 1,388
  • 5
  • 20
  • 39

3 Answers3

2

Check for null from FirstOrDefault() before checking teamviewerID. If you're using C#6, add a ? after FirstOrDefault(). The null check is significantly faster than throwing an exception.

Non C#6:

var myItem = item.tbl_computerinfo.FirstOrDefault();
if (myItem != null && myItem.teamviewerID != null)
{
    <td class="text-center"><a href="javascript:TeamviewerConnect(@Html.DisplayFor(modelItem => item.tbl_computerinfo.FirstOrDefault().teamviewerID)"><img src="~/Content/images/icons/teamviewericon.png" alt='TeamviewerID' border='0' title='@Html.DisplayFor(modelItem => item.tbl_computerinfo.FirstOrDefault().teamviewerID)'></a></td>
}
else
{
    <td></td>
}

C#6:

if (item.tbl_computerinfo.FirstOrDefault()?.teamviewerID != null)
{
    <td class="text-center"><a href="javascript:TeamviewerConnect(@Html.DisplayFor(modelItem => item.tbl_computerinfo.FirstOrDefault().teamviewerID)"><img src="~/Content/images/icons/teamviewericon.png" alt='TeamviewerID' border='0' title='@Html.DisplayFor(modelItem => item.tbl_computerinfo.FirstOrDefault().teamviewerID)'></a></td>
}
else
{
    <td></td>
}
Lathejockey81
  • 1,198
  • 7
  • 8
  • This worked - thank you. Figure out I wasn't even using C#6 despite me being in VS 2015. Thanks. Fixed this by targeting the C#6 in advanced build properties on project and running Install-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform – Trinitrotoluene Jan 31 '16 at 21:12
1

You say you know that the property may not be there, then just check that property instead?

if (item != null)

Or which property you're referring to.

Kristoffer Jälén
  • 4,112
  • 3
  • 30
  • 54
1

Just check for null:

Computerinfo i = item.tbl_computerinfo.FirstOrDefault();
if(i != null) {
    ...
}
romanoza
  • 4,775
  • 3
  • 27
  • 44