I have a property that I’d like to type as int? in my Settings.settings file. When I use int? I get a runtime failure:
System.NullReferenceException: Object reference not set to an instance of an object..
I can use a string type as a workaround where a check for null works, but I have to parse the string and handle errors when the parse doesn’t work.
Being able to set the value to null allows me to keep the property documented in the settings file while making it obvious that no value has been set. When not set I use a programmed default value:
int? configuredNumberOfLimits = Settings.Default.RequiredNumberOfLimits;
if ( configuredNumberOfLimits == null )
{
requiredNumberOfLimits = DEFAULT_REQUIRED_NUMBER_LIMITS;
}
There is a way to use nullable type (i.e.
int?) for a setting – it requires a bit of manual editing of the settings file, but afterwards works fine in VS environment and in the code. And requires no additional functions or wrappers.To do this, create a setting with desired name (e.g. RequiredNumberOfLimit) and make it of any type (e.g. standard
intfor convenience).Save the changes.
Now go to your project folder and open the “Properties\Settings.settings” file with text editor (Notepad, for example) Or you can open it in VS by right-clicking in Solution Explorer on “<Your Project> -> Properties -> Settings.settings”, select “Open With…” and then choose either “XML Editor” or “Source Code (Text) Editor”.
In the opened xml settings find your setting (it will look like this):
Change the “Type” param from
System.Int32toSystem.Nullable<System.Int32>. And also clear the default value (so null could be used there by default).Now this section should look like this (note that
<and>are used to represent<and>symbols inside the type string – this is done for correct parsing of xml by VS):Now save changes and re-open project settings – voilà! – we have the setting RequiredNumberOfLimit with type
System.Nullable<System.Int32>which is parsed correctly by VS Settings Designer, as well as it could be used as a normalint?variable in the code.If you want this setting to be able to return
nullyou should keep the default value field clear.Otherwise, the default value will be returned by this setting if it was assigned to null previously (but thats how the default values work, don’t they? :P).