Often when working within Umbraco, you will need to work with content of type IContent
. When you work with IContent
you don't necessarily know the underlining document type you are working with. This means you might try and access a property on an item that does not exist. If you try and use GetValue()
on a property that doesn't exist, Umbraco will throw a 'The given key was not present in the dictionary' exception.
If you find yourself in this situation, you can use HasProperty()
to check the property exists before you attempt to access it.
Just because you use HasProperty()
doesn't guarantee that the property contains a value. All this code does is check that the property exists. No the value. To get around this, you can use GetValue()
. The code to do this looks like this:
If you need to check that a property exists and has a value, you could do something like this:
If you are working IPublishedContent
you can do something similar and use HasValue()
instead.
Armed with this new knowledge, you should be able to create more defensive and robust code. Happy Coding 🤘