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:)

1
  • what is the warning that is displayed by resharper? Commented Aug 18, 2010 at 6:38

1 Answer 1

3

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.)

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.