//C# Generic String Parser Extension Method using System; using System.ComponentModel; public class Test { public static void Main() { string s = "32"; int i = s.As() + 10; Console.WriteLine(i); string b = "false"; if(b.As()) { Console.WriteLine("True"); } else { Console.WriteLine("False"); } } } /* C# Generic String Parser Extension Method Usage Example string s = "32"; int i = s.As(); */ public static class StringExtensions { public static T As(this string strValue, T defaultValue) { T output = defaultValue; if (output == null) { output = default(T); } TypeConverter converter = TypeDescriptor.GetConverter(typeof(T)); if (converter != null) { try { output = (T)converter.ConvertFromString(strValue); } catch (Exception ex) { throw ex; } } return output; } public static T As(this string strValue) { return strValue.As(default(T)); } }