ZipCode Struct With Parser
CodeKeep C# Feed Giugno 5th, 2008
Description: ZipCode structure that takes a zip code on the constructor and parses it to Zip & Zip+4 if it’s valid. Sets it to nothing otherwise
Link: http://www.codekeep.net/snippets/a630ce70-b87e-4cdf-9cd2-1013b5e48d48.aspx
truct ZipCode
{
private string m_Zip;
public string Zip
{
get { return m_Zip; }
set { m_Zip = value; }
}
private string m_Zip4;
public string Zip4
{
get { return m_Zip4; }
set { m_Zip4 = value; }
}
public override string ToString()
{
if (String.IsNullOrEmpty(Zip) || Zip.Length != 5) { return String.Empty; }
if (String.IsNullOrEmpty(Zip4) || Zip4.Length != 4)
{
return Zip;
}
else
{
return Zip + "-" + Zip4;
}
}
public ZipCode(string zip)
{
string regularExpression = "^(?<Zip>\\d{5})-{0,1}(?<Zip4>(\\d{4}){0,1})$";
Regex reg = new Regex(regularExpression);
Match match = reg.Match(zip);
if (match != null && match.Success)
{
m_Zip = match.Groups["Zip"].Value;
m_Zip4 = match.Groups["Zip4"].Value;
}
else
{
m_Zip = String.Empty;
m_Zip4 = String.Empty;
}
}
}






