fork(1) download
  1. //C# Generic String Parser Extension Method
  2. using System;
  3. using System.ComponentModel;
  4.  
  5. public class Test
  6. {
  7. public static void Main()
  8. {
  9. string s = "32";
  10. int i = s.As<int>() + 10;
  11. Console.WriteLine(i);
  12. string b = "false";
  13. if(b.As<bool>())
  14. {
  15. Console.WriteLine("True");
  16. }
  17. else
  18. {
  19. Console.WriteLine("False");
  20. }
  21. }
  22. }
  23.  
  24.  
  25. /*
  26. C# Generic String Parser Extension Method
  27. Usage Example
  28. string s = "32";
  29. int i = s.As<int>();
  30. */
  31. public static class StringExtensions
  32. {
  33. public static T As<T>(this string strValue, T defaultValue)
  34. {
  35. T output = defaultValue;
  36. if (output == null)
  37. {
  38. output = default(T);
  39. }
  40. TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
  41. if (converter != null)
  42. {
  43. try
  44. {
  45. output = (T)converter.ConvertFromString(strValue);
  46. }
  47. catch (Exception ex)
  48. {
  49. throw ex;
  50. }
  51. }
  52.  
  53. return output;
  54. }
  55.  
  56. public static T As<T>(this string strValue)
  57. {
  58. return strValue.As<T>(default(T));
  59. }
  60. }
Success #stdin #stdout 0.06s 37320KB
stdin
Standard input is empty
stdout
42
False