I want the ability to reset a single user setting easily to its default value. I've written an extension like so:
public static void sReset(this Properties.Settings set, string key = "")
{
if (key == "")
{
set.Reset();
return;
}
Console.WriteLine("Reset '" + key + "' to: " + set.Properties[key].DefaultValue);
set.PropertyValues[key].PropertyValue = set.PropertyValues[key].Property.DefaultValue;
}
And this works fine for primitive types. But now I want to apply that to a stringCollection, and it fails:
An unhandled exception of type 'System.InvalidCastException' occurred in myApp.exe
Additional information: Unable to cast object of type 'System.String' to type 'System.Collections.Specialized.StringCollection'.
This is because these collection type default values (Stored serialized as XML) are returned as strings:
set.Properties[key].DefaultValue.GetType() returns System.String
I can see in the settings designer that usually, it just casts the value to StringCollection:
public global::System.Collections.Specialized.StringCollection settingsName {
get {
return ((global::System.Collections.Specialized.StringCollection)(this["settingsName"]));
}
set {
this["settingsName"] = value;
}
}
But that fails after assigning the DefaultValue, with the above error message.
I tried casting the XML String before assigning, but of course that failed there, too.
How is an XML String like this converted before being assigned to the settings property? What do I need to do to make this work?