Friday, May 4, 2012

Converting from string to type


//Converting from string to type
//Generic code for converting a string to a specific type

public static T FromString<T>(string text)
        {
            try
            {
                return (T)Convert.ChangeType(text, typeof(T), CultureInfo.InvariantCulture);
            }
            catch
            {
                return default(T);
            }
        }

public static T FromXmlAttribute<T>(XmlNode node, string attributeName)
        {
            if(node == null)
                throw new ArgumentNullException("node");

            if(String.IsNullOrEmpty(attributeName))
                throw new ArgumentException("Cannot be null or empty", "attributeName");

            XmlAttribute attribute = node.Attributes[attributeName];
            if(attribute == null)
                return default(T);

            return FromString<T>(attribute.Value);
        }

public static T FromXAttribute<T>(XElement element, string attributeName)
        {
            if (element == null)
                throw new ArgumentNullException("element");

            if (String.IsNullOrEmpty(attributeName))
                throw new ArgumentException("Cannot be null or empty", "attributeName");

            XAttribute attribute = element.Attribute(attributeName);
            if (attribute == null)
                return default(T);

            return FromString<T>(attribute.Value);
        }

No comments: