5

I would like to use ConfigurationManager to access some string values from a static class. However, I need to handle specifically the absence of a value or the presence of empty values. Right now I was using type initializers, like

private static readonly string someStr = ConfigurationManager.AppSettings["abc"];

to do the job. However, if a string with key "abc" doesn't exist in App.config the execution will happilly continue with a null reference in place of someStr. What is, then, the best way to validate this value on initialization? A static constructor in which I initialize the value and then check for validity? I heard static constructors are to be avoided and replaced by type initializers when possible.

3 Answers 3

7

I'm using something like this:

public static readonly string someStr  = 
        ConfigurationManager.AppSettings["abc"] ?? "default value";

Or to handle empty string:

public static readonly string someStr = 
           !String.IsNullOrEmpty(ConfigurationManager.AppSettings["abc"]) ? 
                             ConfigurationManager.AppSettings["abc"] : "default value";
Sign up to request clarification or add additional context in comments.

Comments

5

This just came up in a code review. The answers provided are great for strings. But they don't work for an int or a double, etc... Today, I needed to do this for a retry count and it needs to be an int.

So here is an answer for those who want Type conversion included.

Use this extension method:

using System.Collections.Specialized;
using System.ComponentModel;

namespace Rhyous.Config.Extensions
{
    public static class NameValueCollectionExtensions
    {
        public static T Get<T>(this NameValueCollection collection, string key, T defaultValue)
        {
            var value = collection[key];
            var converter = TypeDescriptor.GetConverter(typeof(T));
            if (string.IsNullOrWhiteSpace(value) || !converter.IsValid(value))
            {
                return defaultValue;
            }

            return (T)(converter.ConvertFromInvariantString(value));
        }
    }
}

I also have unit tests for it, which you can find here: http://www.rhyous.com/2015/12/02/how-to-easily-access-a-web-config-appsettings-value-with-a-type-and-a-default-value

Hope that helps the next guy.

3 Comments

This is now in my Rhyous.Collections NuGet package and you can see the source on GitHub: github.com/rhyous/Collections/blob/master/src/…
Would it make sense to constraint T as convertible, i.e., where T : IConvertible? I don't think we're ever going to try to get the key value with a struct or class default value.
You might be correct. I am not sure why I didn't do this.
3

static constructors are fine, the great thing about them is that they are guaranteed by the runtime to be executed once and once only - the first time the class is used in any circumstance.

You could alternatively use the coalesce operator (??) to set a default value:

private static readonly string someStr = ConfigurationManager.AppSettings["abc"] ?? "some default value";

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.