Object reference exception when accessing farm properties

Here is a problem I had and it took me a while to know the reason behind it, it’s when you try to add a farm property using PowerShell, like this:

Now try to get the farm properties using the following command: $farm.properties, you will see the following result:

that’s great! You could get your property name and value without any problems, so now let’s try to get the farm property in code, shall we?

In visual studio type the following in your code:

String myProperty = SPFarm.Local.Properties[“MyFirstProperty”].ToString();

Baaaaaam, you will get: object reference not set to an instance of an object.

The reason is, although you can see the farm property in PowerShell when you type $farm.properties, you need to write the $farm.update() command after that in order to be able to use that property and to be visible in your code.

Hope this helps someone out there.