/// <summary> /// Gets the value. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <param name="keyName">Name of the key.</param> /// <param name="defaultValue">if set to <c>true</c> [default value].</param> /// <param name="booleanConverter">The boolean converter.</param> /// <returns></returns> public virtual bool GetValue(string sectionName, string keyName, bool defaultValue, BooleanConverter booleanConverter = null) { booleanConverter = booleanConverter ?? Settings.BooleanConverter; var booleanValue = GetRawValue <string>(sectionName, keyName, null); if (string.IsNullOrWhiteSpace(booleanValue)) { SetValue(sectionName, keyName, null == booleanConverter // if some day Boolean.ToString(IFormatProvider) will work // https://msdn.microsoft.com/en-us/library/s802ct92(v=vs.110).aspx#Anchor_1 ? defaultValue.ToString(Settings.Culture).ToLowerInvariant() : booleanConverter.ConvertToString(defaultValue)); return(defaultValue); } #pragma warning disable IDE0046 // Convert to conditional expression foreach (var converter in YesNoBoolConverters) { if (converter.Yes.Equals(booleanValue.Trim(), StringComparison.InvariantCultureIgnoreCase) || converter.No.Equals(booleanValue.Trim(), StringComparison.InvariantCultureIgnoreCase)) { return(converter.Yes.Equals(booleanValue, StringComparison.InvariantCultureIgnoreCase)); } } #pragma warning restore IDE0046 // Convert to conditional expression if (bool.TryParse(booleanValue, out var parseBoolean)) { return(parseBoolean); } // if some day Boolean.ToString(IFormatProvider) will work // https://msdn.microsoft.com/en-us/library/s802ct92(v=vs.110).aspx#Anchor_1 if (true.ToString(Settings.Culture).ToLowerInvariant().Equals(booleanValue, StringComparison.InvariantCultureIgnoreCase)) { return(true); } if (booleanConverter == null || !booleanConverter.CanConvertFrom(typeof(string))) { return(defaultValue); } var value = booleanConverter.ConvertFrom(booleanValue); return(value is bool convertedBoolean ? convertedBoolean : defaultValue); }
/// <summary> /// Converts the string value to a boolean. Int32 values are able to be /// parsed. /// </summary> /// <typeparam name = "T"></typeparam> /// <param name = "value"></param> /// <returns></returns> private static T ConvertToBool <T>(string value) { // see if an int was used. 0 = false, anything else is true. int result; if (Int32.TryParse(value, out result)) { return((T)(object)(result != 0)); } // didn't use an int, pass off the the BooleanConverter. The // BooleanConverter can't handle numbers and it is faster to check // if it is an int than deal with the exception that the // BooleanConverter would throw and then deal with converting from // int. var converter = new BooleanConverter(); return((T)converter.ConvertFrom(value)); }