tags:

views:

40

answers:

1

In the following code, How can I check for null reference exception in a "good practice" way?

if (primaryMenu.ChildNodes.Any(p=>VirtualPathUtility.GetFileName(p.SiteURL).Equals(selectedPage)))
{
   primaryMenuTab.Attributes.Add("class", "current");
}

The way I am doing it currently is (But JetBrain ReSharper doesnt't wana accept it and keep warning me on the following part : VirtualPathUtility.GetFileName(p.SiteURL) which is understandable),

if (primaryMenu.ChildNodes.Any(p=> p.SiteURL != null && VirtualPathUtility.GetFileName(p.SiteURL).Equals(selectedPage)))
{
   primaryMenuTab.Attributes.Add("class", "current");
}

Where Menus have the following structure,

public class MultiLevelMenuNodeList
 {
  public string Name { get; set; }
  public string Permission { get; set; }
  public string SiteURL { get; set; }
  public string Visibility { get; set; }
  public List<SingleLevelMenuNodeList> ChildNodes { get; set; }
 }

 public class SingleLevelMenuNodeList
 {
  public string Name { get; set; }
  public string Permission { get; set; }
  public string SiteURL { get; set; }
  public string Visibility { get; set; }
  public string TabPosition { get; set; }
 }

Thanks in advance for suggestions and tips. I am kinda getting addicted to stackoverflow:)

+3  A: 

A simple solution is to just use == which is null-safe:

if (primaryMenu.ChildNodes.Any(p =>
        VirtualPathUtility.GetFileName(p.SiteURL) == selectedPage))

(That's assuming GetFileName itself can cope with null input; otherwise put your first null check back in.)

Jon Skeet
@shashkalpesh it shows Possible 'System.NullReferenceException'@Jon Thanks :) I will use that and see how it goes.
MSI
Yup ReSharper is not showing any warning when I use ==. Thanks
MSI