In SharePoint there are “property bags” on many elements of the system. For example, SPWebs and SPFolders have them, and methods like GetProperty() and SetProperty() to set them.
These methods accept and return objects. However, it’s nice to get values back in the same form as they were set.
To set a property, you can use code like this:
SPFolder f = list.RootFolder; f.SetProperty("PropertyA", 12); f.SetProperty("PropertyB", "Hello"); f.Update();
To retrieve a property, for a reference type like a string, you can use:
string propB = f.GetProperty("PropertyB") as string;
‘propB’ will be null if the property was empty or not a string, otherwise it will be a string containing the original value.
What about value types, though, such as property A? Well, again, we can use an ‘as’ operator – but this can return null, so we might need to use a nullable value type, and then coalesce the nullable type into the one we want. For example:
int? nullableOutput = f.GetProperty("PropertyA") as int?; int output = nullableOutput ?? 1;
This will get property A as a nullable int. If the property is unset or not an int, it will get a null. We then set an int based on the nullable one – if the nullable value is null, we set it to 1.