I’m storing some common settings used in a C# program inside the ApplicationSettings. Most of the settings are strings, but one of them is a StringCollection.
A null exception is occurring in some code that loops through the default settings at Properties.Settings.Default and adds them to a dictionary (in preparation to send as parameters), as shown below.
// Generate parameters
Dictionary<string, string> signalparams = new Dictionary<string, string>();
// Add parameters
foreach (SettingsProperty property in Properties.Settings.Default.Properties)
{
SettingsPropertyValue value = new SettingsPropertyValue(property);
if (value.Property.SerializeAs == SettingsSerializeAs.Xml)
{
// Here's where the error occurs
signalparams.Add(value.Name, value.SerializedValue.ToString());
}
else if (value.Property.SerializeAs == SettingsSerializeAs.String)
{
signalparams.Add(value.Name, value.PropertyValue.ToString());
}
}
The strings settings are added fine, but when it reaches the StringCollection, it (correctly) evaluates that the property has SerializeAs == SettingsSerializeAs.Xml. However, the SerializedValue is null, and thus ToString() throws an exception.
The strange thing is that when running the debugger, the SerializedValue is null until I try viewing the value variable’s properties in the locals windows. At that point, SerializedValue contains the correct XML serialized format for the StringCollection, and the program continues fine.
Why is this happening?
The issue stems probably from the fact that
SerializedValueis a property that is implemented something like that:What happens in your case, in my opinion, is that you’re getting _cachedData when you first access the SettingPropertyValue, then, by viewing
valuevia the debugger, you cause_ChangedSinceLastSerializedto betruewhich causes the next call toSerializedValueproperty to return the actual serialized value.The next question is to find out why
_ChangedSinceLastSerializedin your case is set tofalse. The logic ofSettingsPropertyValuesays (you can see it in Reflector inPropertyValueproperty of the class) that_ChangedSinceLastSerializedis set to true when the user either accesses the settings (in case of most object types), so for example merely accessing your setting like that: MyAppSettings.Default.MySettingObject would change_ChangedSinceLastSerializedtotrue.What could happen in your case that you have code similar to this:
Once you do something like that and keep using
storingObjectinstead of directly accessingMyAppSettingsyou can create a situation in which the object changed while_ChangedSinceLastSerializedremainsfalse.I hope that was helpful.