2

I have an int setting in appsettings.json that I read from C#:

const int HardCodedDefault = 42;
int settingValue = configuration.GetValue<int>("myKey", HardCodedDefault);

Unfortunately, I can't find a way to put only the key in the appsettings.json file (so I can specify a value if I want it, but otherwise let it fall back to the default). Both null and the empty string throw an exception:

Failed to convert configuration value at 'myKey' to type 'System.int32'

1 Answer 1

5

Because your appsettings.json file holds an item with key "myKey", the specified conversion to int will always get executed regardless of whether the corresponding value is a valid int or is null or is an empty string. This conversion will obviously fail for those last 2.

Only converting to int? won't be enough since the null value found will not trigger the provided default value being applied, because the default value for int? is null.

A possible solution to deal with all scenarios where the item in appsettings.json is missing or holds a null value or holds a empty string value is below one, which doesn't provide a default value to the GetValue method, but relies on the null-coalescing operator.

var settingValue = configuration.GetValue<int?>("myKey") ?? HardCodedDefault;

appsettings.json

{
  "myKey": null
}

Alternatively, you can just put that setting as a comment in your appsettings.json file, which represents the missing key scenario, returning the default value passed to GetValue.

{
  // "myKey": null
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.