Search code examples
c#zipcode

What's a better way to write this?


public string SomeMethod(string  OriginalZip) {

     string zip = "Zip Not Available";
     zip = GetZip(zip, OriginalZip);
     return zip;
 }
 
private static string GetZip(string zip, string OriginalZip)
{

     int zipLength = (OriginalZip.HasValue) ? OriginalZip.Value.ToString().Length : 0;
     int NumOfLeadingZeroes = (zipLength > 0 && zipLength < 5) ? 5 - zipLength : 0;


    if (OriginalZip.HasValue)
     {
         zip = OriginalZip.Value.ToString();
         for (int i = 0; i < NumOfLeadingZeroes; i++)
         {
             zip = "0" + zip;
         }
     }
  
    return zip;
 }

Solution

  • Let's try to state the problem (reverse engineering) and then solve it. As far as I can see, we want to pad 0 from the left for zip to have at least 5 digits. If your case then

    private static string GetZip(string value) => string.IsNullOrEmpty(value)
      ? new string('0', 5)
      : value.PadLeft(5, '0');
    

    usage:

    public string SomeMethod(string originalZip) {
      string zip = GetZip(originalZip);
    
      ...
    }