/// <summary> /// Changes the type (with extended handling for booleans and empty strings). /// </summary> /// <param name="value">The value.</param> /// <param name="tgtType">Type of the TGT.</param> /// <param name="culture">The culture.</param> /// <returns></returns> public static object ChangeTypeExtended(object value, Type tgtType, CultureInfo culture = null) { if (tgtType == null) { return(value); } object tgtValue = null; if ((tgtType == typeof(bool) || tgtType == typeof(bool?)) && value is string) { // Special handling for Boolean string strValue = (value as string).Trim().ToLower(); if (strValue == "1" || strValue == "true" || strValue == "yes" || strValue == "y") { tgtValue = true; } else { tgtValue = false; } } else if (tgtType != typeof(string) && string.IsNullOrWhiteSpace(value.ToStringOrEmpty())) { // special handling for whitespace strings, for non string types tgtValue = Activator.CreateInstance(tgtType); } else { tgtValue = ConvertExtensions.ChangeType(value, tgtType, culture); } return(tgtValue); }
/// <summary> /// Gets the attribute value. /// </summary> /// <param name="element">The element.</param> /// <param name="name">The name.</param> /// <param name="defaultValue">The default Value.</param> /// <returns></returns> public static T GetAttributeValue <T>(this XElement element, string name, T defaultValue = default(T)) { XAttribute xAttribute = element.Attribute(XName.Get(name)); if (xAttribute == null) { return(defaultValue); } if (typeof(T) == typeof(bool)) { object objvalue; bool boolValue; Boolean.TryParse(xAttribute.Value.ToLower(), out boolValue); objvalue = boolValue; return((T)objvalue); //object value = XmlConvert.ToBoolean(xAttribute.Value); //return (T)value; } return(ConvertExtensions.ConvertTo <T>(xAttribute.Value)); }