using System.Text.RegularExpressions;
public static void Main()
TimerExpression("TryParse",
for (int i = 0; i < max; i++)
Int32.TryParse(i.ToString(), out value);
for (int i = 0; i < max; i++)
Regex.IsMatch(i.ToString(), @"\d");
TimerExpression("PHP IsNumeric",
for (int i = 0; i < max; i++)
i.ToString().IsNumeric();
TimerExpression("Reflections TryParse",
for (int i = 0; i < max; i++)
i.ToString().ParseAs<int>(0);
public static void TimerExpression(string label, Action call)
var watch = System.Diagnostics.Stopwatch.StartNew();
System.Console.WriteLine(label + " " + watch.ElapsedMilliseconds.ToString());
public static class StringExtension
public static TOutput ParseAs<TOutput>(this string value, TOutput defaultValue)
var type = typeof(TOutput);
var tryParseMethod = type.GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder, new[] { typeof(string), type.MakeByRefType() }, null);
if (tryParseMethod == null) return defaultValue;
var arguments = new object[] { value, null };
return ((bool)tryParseMethod.Invoke(null, arguments)) ? (TOutput)arguments[1] : defaultValue;
static readonly Regex _isNumericRegex =
@"((?!0)|[-+]|(?=0+\.))(\d*\.)?\d+(e\d+)?" +
public static bool IsNumeric(this string value)
return _isNumericRegex.IsMatch(value);