First you need to define a format that your type will follow when being converted to a string.
A simple example is a social security number. You can easily describe it as a regular expression.
\d{3}-\d{2}-\d{4}
After that you simple need to reverse the process. The convention is to define a Parse
method and a TryParse
method for your type. The difference being that TryParse
will not throw an exception.
public static SSN Parse(string input)
public static bool TryParse(string input, out SSN result)
Now the process you follow to actually parse the input string can be as complex or as simple as you wish. Typically you would tokenize the input string and perform syntactic validation. (EX: Can a dash go here?)
number
dash
number
dash
number
It really depends on how much work you want to put into it. Here is a basic example of how you might tokenize a string.
private static IEnumerable<Token> Tokenize(string input)
{
var startIndex = 0;
var endIndex = 0;
while (endIndex < input.Length)
{
if (char.IsDigit(input[endIndex]))
{
while (char.IsDigit(input[++endIndex]));
var value = input.SubString(startIndex, endIndex - startIndex);
yield return new Token(value, TokenType.Number);
}
else if (input[endIndex] == '-')
{
yield return new Token("-", TokenType.Dash);
}
else
{
yield return new Token(input[endIndex].ToString(), TokenType.Error);
}
startIndex = ++endIndex;
}
}