Skip to content

Instantly share code, notes, and snippets.

@atsvetkov
Last active December 25, 2016 19:20
Show Gist options
  • Save atsvetkov/e7d9d75da433a827a9325bd850ae9a07 to your computer and use it in GitHub Desktop.
Save atsvetkov/e7d9d75da433a827a9325bd850ae9a07 to your computer and use it in GitHub Desktop.
public static class IntegerParser
{
private const int MinDigit = '0';
private const int MaxDigit = '9';
public static bool TryParse(object number, out int result)
{
if (number is int)
{
result = (int)number;
return true;
}
if (number is string)
{
return ParseString((string)number, out result);
}
throw new NotSupportedException($"{nameof(IntegerParser)} only accepts strings ans integers, type '{number.GetType()}' is not supported");
}
private static bool ParseString(string number, out int result)
{
result = 0;
for (var i = 0; i < number.Length; i++)
{
var charCode = (int)number[i];
if (charCode < MinDigit || charCode > MaxDigit)
{
return false;
}
result = result * 10 + (charCode - MinDigit);
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment