fork download
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. public static class GenericParser
  5. {
  6. //create a delegate which our parsers will use
  7. private delegate bool Parser(string source, out object result);
  8.  
  9. //This is the list of our parsers
  10. private static readonly List<Parser> Parsers = new List<Parser>
  11. {
  12. new Parser(ParseInt),
  13. new Parser(ParseDouble),
  14. new Parser(ParseBool),
  15. new Parser(ParseString)
  16. };
  17.  
  18. public static object Parse(string source)
  19. {
  20. object result;
  21. foreach (Parser parser in Parsers)
  22. {
  23. //return the result if the parser succeeded.
  24. if (parser(source, out result))
  25. return result;
  26. }
  27.  
  28. //return null if all of the parsers failed (should never happen because the string->string parser can't fail.)
  29. return null;
  30. }
  31.  
  32. private static bool ParseInt(string source, out object result)
  33. {
  34. int tmp;
  35. bool success = int.TryParse(source, out tmp);
  36. result = tmp;
  37. return success;
  38. }
  39.  
  40. private static bool ParseDouble(string source, out object result)
  41. {
  42. double tmp;
  43. bool success = double.TryParse(source, out tmp);
  44. result = tmp;
  45. return success;
  46. }
  47.  
  48. private static bool ParseBool(string source, out object result)
  49. {
  50. bool tmp;
  51. bool success = bool.TryParse(source, out tmp);
  52. result = tmp;
  53. return success;
  54. }
  55.  
  56. private static bool ParseString(string source, out object result)
  57. {
  58. result = source;
  59. return true;
  60. }
  61. }
  62.  
  63. public class Test
  64. {
  65. static void Main(string[] args)
  66. {
  67. TestString("2");
  68. TestString("2.0");
  69. TestString("true");
  70. TestString("nnn");
  71. }
  72.  
  73. static void TestString(string testString)
  74. {
  75. object result = GenericParser.Parse(testString);
  76. Console.WriteLine("\"{0}\"\t => {1}", testString, result.GetType().Name);
  77. }
  78. }
Success #stdin #stdout 0.06s 34056KB
stdin
Standard input is empty
stdout
"2"	 => Int32
"2.0"	 => Double
"true"	 => Boolean
"nnn"	 => String