Home
Manage Your Code
Snippet: ZipCode Struct With Parser (C#)
Title: ZipCode Struct With Parser Language: C#
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 Views: 322
Author: Andrew Faust Date Added: 6/5/2008
Copy Code  
1struct ZipCode
2        {
3            private string m_Zip;
4            public string Zip
5            {
6                get { return m_Zip; }
7                set { m_Zip = value; }
8            }
9
10            private string m_Zip4;
11            public string Zip4
12            {
13                get { return m_Zip4; }
14                set { m_Zip4 = value; }
15            }
16
17            public override string ToString()
18            {
19                if (String.IsNullOrEmpty(Zip) || Zip.Length != 5) { return String.Empty; }
20                if (String.IsNullOrEmpty(Zip4) || Zip4.Length != 4)
21                {
22                    return Zip;
23                }
24                else
25                {
26                    return Zip + "-" + Zip4;
27                }
28            }
29
30            public ZipCode(string zip)
31            {
32                string regularExpression = "^(?<Zip>\\d{5})-{0,1}(?<Zip4>(\\d{4}){0,1})$";
33                Regex reg = new Regex(regularExpression);
34                Match match = reg.Match(zip);
35
36                if (match != null && match.Success)
37                {
38                    m_Zip = match.Groups["Zip"].Value;
39                    m_Zip4 = match.Groups["Zip4"].Value;
40                }
41                else
42                {
43                    m_Zip = String.Empty;
44                    m_Zip4 = String.Empty;
45                }
46            }
47        }
Usage
Requires System.Text.RegularExpressions