Skip to main content

C# extension methods for IConfiguration.

using System;
using Microsoft.Extensions.Configuration;

public static class ConfigurationExtensions
{
    public static string GetValueOrDefault(this IConfiguration value, string key, string defaultValue)
    {
        var configValue = value.GetValue<string>(key);
        return string.IsNullOrWhiteSpace(configValue) ? defaultValue : configValue;
    }

    public static int GetValueOrDefault(this IConfiguration value, string key, int defaultValue)
    {
        return int.TryParse(value.GetValue<string>(key), out int configValue) ? configValue : defaultValue;
    }

    public static int? GetValueOrDefault(this IConfiguration value, string key, int? defaultValue)
    {
        var configValueString = value.GetValue<string>(key);
        if (!string.IsNullOrWhiteSpace(configValueString))
        {
            return int.TryParse(configValueString, out int configValue) ? configValue : defaultValue;
        }
        
        return defaultValue;
    }

    public static bool GetValueOrDefault(this IConfiguration value, string key, bool defaultValue)
    {
        return bool.TryParse(value.GetValue<string>(key), out bool configValue) ? configValue : defaultValue;
    }

    public static TEnum GetValueOrDefault<TEnum>(this IConfiguration value, string key, TEnum defaultValue) where TEnum : struct
    {
        return Enum.TryParse<TEnum>(value.GetValue<string>(key), true, out TEnum configValue) ? configValue : defaultValue;
    }
}