fork(1) download
  1. using System;
  2. using System.Reflection;
  3.  
  4. public delegate bool TryParser<T>(string s, out T result);
  5.  
  6. public static class Parser
  7. {
  8. public static bool TryParse<T>(string s, out T result)
  9. {
  10. return Inner<T>.parser(s, out result);
  11. }
  12.  
  13. public static T? ParseOrNull<T>(string s)
  14. where T : struct
  15. {
  16. T result;
  17. if (TryParse<T>(s, out result)) return result;
  18. else return null;
  19. }
  20.  
  21. static class Inner<T>
  22. {
  23. public static TryParser<T> parser;
  24.  
  25. static Inner()
  26. {
  27. var m = typeof(T).GetMethod("TryParse", new[] { typeof(string), typeof(T).MakeByRefType() });
  28.  
  29. if (m == null)
  30. throw new NotSupportedException();
  31.  
  32. parser = (TryParser<T>)Delegate.CreateDelegate(typeof(TryParser<T>), m);
  33. }
  34. }
  35. }
  36.  
  37. class Program
  38. {
  39. static void Main()
  40. {
  41. Console.WriteLine(Parser.ParseOrNull<int>("1234"));
  42. Console.WriteLine(Parser.ParseOrNull<int>("12a34"));
  43. Console.WriteLine(Parser.ParseOrNull<int>("12344aq"));
  44. Console.WriteLine(Parser.ParseOrNull<int>("123safw4"));
  45. Console.WriteLine(Parser.ParseOrNull<double>("1.234"));
  46. Console.WriteLine(Parser.ParseOrNull<double>("12.34"));
  47. Console.WriteLine(Parser.ParseOrNull<double>("12.a34"));
  48.  
  49. Func<string, byte?> parser = Parser.ParseOrNull<byte>;
  50.  
  51. Console.WriteLine(parser("255"));
  52. }
  53. }
  54.  
Success #stdin #stdout 0.05s 38184KB
stdin
Standard input is empty
stdout
1234



1.234
12.34

255