Home
Manage Your Code
Snippet: Converting from string to type (C#)
Title: Converting from string to type Language: C#
Description: Generic code for converting a string to a specific type Views: 330
Author: Oded Levy Date Added: 11/27/2008
Copy Code  
1	public static T FromString<T>(string text)
2        {
3            try
4            {
5                return (T)Convert.ChangeType(text, typeof(T), CultureInfo.InvariantCulture);
6            }
7            catch
8            {
9                return default(T);
10            }
11        }
12
13	public static T FromXmlAttribute<T>(XmlNode node, string attributeName)
14        {
15            if(node == null)
16                throw new ArgumentNullException("node");
17
18            if(String.IsNullOrEmpty(attributeName))
19                throw new ArgumentException("Cannot be null or empty", "attributeName");
20
21            XmlAttribute attribute = node.Attributes[attributeName];
22            if(attribute == null)
23                return default(T);
24
25            return FromString<T>(attribute.Value);
26        }
27
28	public static T FromXAttribute<T>(XElement element, string attributeName)
29        {
30            if (element == null)
31                throw new ArgumentNullException("element");
32
33            if (String.IsNullOrEmpty(attributeName))
34                throw new ArgumentException("Cannot be null or empty", "attributeName");
35
36            XAttribute attribute = element.Attribute(attributeName);
37            if (attribute == null)
38                return default(T);
39
40            return FromString<T>(attribute.Value);
41        }