Skip to content

Instantly share code, notes, and snippets.

@atsvetkov
Created December 25, 2016 21:34
Show Gist options
  • Save atsvetkov/c9353788acac9eab9f5851bda321272f to your computer and use it in GitHub Desktop.
Save atsvetkov/c9353788acac9eab9f5851bda321272f to your computer and use it in GitHub Desktop.
public static (bool success, int result) TryParse(object number)
{
switch (number)
{
case int i:
return (true, i);
case string s:
(bool isParsed, int value) ParseString(string str)
{
var res = 0;
for (var i = 0; i < str.Length; i++)
{
var charCode = (int)str[i];
if (charCode < MinDigit || charCode > MaxDigit)
{
return (false, res);
}
res = res * 10 + (charCode - MinDigit);
}
return (true, res);
}
return ParseString(s);
default:
throw new NotSupportedException($"{nameof(IntegerParser)} only accepts strings ans integers, type '{number.GetType()}' is not supported");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment