C Sharp: Under-utilized Padleft() method

What I am going to explain is not for a specific situation, we can use it in so many cases. I am talking about PadLeft() method of string class. To explain it, I am just showing you an example, which I found somebody doing while he is supposed to code for three dropdowns like Day,Month & Year. Following is the snippet of his code-

private void bindDay()
    {        
        ArrayList day = new ArrayList();
        for (var i = 1; i <= 31; i++)
        {
            if (i > 0 && i < 10)
            {
                var x = "0" + i;
                day.Add(x);
            }
            else
                day.Add(i);
        }
        ddlDays.DataSource = day;        
        ddlDays.DataBind();
}

Although this block of snippet may need improvements on some other line(s) of code but I am concentrating on the part inside the ‘for loop’. Yes, the if .. else .. block. Here, 5-7 lines of the code is intended to add days of date and with 2-digit format like 01,02,03..etc. I admit that there are so many ways to accomplish it, but I am just talking about the logic. In this code, it has a loop variable which checks the value to find if it is of single digit or two digits. Then if it is of 2-digits then no logic to go before adding it to the dropdownlist and if it is of 1-digit then it is to be padded with a ‘0’..This will work definitely fine for Day dropdown.

Now we can ask what happen when some body wants to form a dropdown with fixed no of 10 digits and a dumb answer will be -“Use 9-10 if..else conditions to do this”.

We can replace the whole if .. else .. by just using a simple method of System.String class – PadLeft(). Now after changing only the if else block with PadLeft(), the code will be like-

private void bindDay()
    {        
        ArrayList day = new ArrayList();
        for (var i = 1; i <= 31; i++)
        {
               day.Add(i.ToString().PadLeft(2,'0'));
        }
        ddlDays.DataSource = day;        
        ddlDays.DataBind();
} 

Here , PadLeft() is taking 2 parameters- width of the resulted string and the character to be padded to the left when string is of length less than 2.
This can also be used to scenarios where you need to generate a code (like Employee Code,Book Code, etc) of a fixed length.

One thought on “C Sharp: Under-utilized Padleft() method

  1. how to send full xml in param to call wcf method.My client side code is in AJAX, JSON Call using jQuery.I want to pass this xml value Myvalue

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s