Skip to content

Instantly share code, notes, and snippets.

@atsvetkov
Created December 25, 2016 20:31
Show Gist options
  • Save atsvetkov/82eef08eb8cd6bdb84e86344d94f096c to your computer and use it in GitHub Desktop.
Save atsvetkov/82eef08eb8cd6bdb84e86344d94f096c to your computer and use it in GitHub Desktop.
public static bool TryParse(object number, out int result)
{
switch (number)
{
case int i:
result = i;
return true;
case string s:
bool ParseString(string str, out int res)
{
res = 0;
for (var i = 0; i < str.Length; i++)
{
var charCode = (int)str[i];
if (charCode < MinDigit || charCode > MaxDigit)
{
return false;
}
res = res * 10 + (charCode - MinDigit);
}
return true;
}
return ParseString(s, out result);
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