Extending Umbraco API with extension methods

Nullreference exception safe property accessing

  • Share

Often during writing partial view for page you need to read value from property which is content or media picker.

In order to get integer value you need to cast value acquired with GetPropertyValue method which is object type.

Ofcourse, before doing the cast, to avoid NullReferenceException you need to check whether property exists and is value not equal to null.

This is fine if you are doing this check and casting only on few places, but often you need to reuse this logic. Copy/Paste is a bad practice and does not enforce code reuse and writing reusable methods. It also increases possibility of potential bugs and makes code very hard to maintain.

The best approach I'm often using are extension methods.

You can store all your Umbraco extension methods to a single library and just add reference and include namespace in every future project you are going to build.

Method GetPropertyValue returns object, which can be null and cause NullReferenceException, so it is useful to have a methods returning string while checking whether object is null.

public static string GetPropertyValueAsString(this IPublishedContent page, string propertyName)
{
    string result = string.Empty;
    if (page.HasProperty(propertyName) && page.GetPropertyValue(propertyName) != null)
    {
		result = page.GetPropertyValue(propertyName).ToString();
    }
    return result;
}
    

This will ensure that you never try to access null object.

Upon this method I wrote few more to make life easier and avoid NullReferenceException.

public static int GetPropertyValueAsInt(this IPublishedContent page, string propertyName)
{
    int result = 0;
    int.TryParse(page.GetPropertyValueAsString(propertyName), out result);
    return result;
}

public static bool GetPropertyValueAsBool(this IPublishedContent page, string propertyName)
{
    bool result = false;
    if (!bool.TryParse(page.GetPropertyValueAsString(propertyName), out result))
    {
		if (page.GetPropertyValueAsString(propertyName) == 1.ToString())
		{
			return true;
		}
		else
		{
			return false;
		}
    }
    return result;
}
    

Class containing these extension methods is attached to this article. To enable using these methods you just need to include the class in you project reference it with using at the beginning of your code.

using Umbraco.Cms.Custom;
    
  • Share

Disclaimer

Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

Comments for this article

comments powered by Disqus