Last active
December 25, 2016 19:20
-
-
Save atsvetkov/e7d9d75da433a827a9325bd850ae9a07 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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