views:

20

answers:

2

I have the following code:

string foo = "blah".PadLeft(4, ' ');

But when I check it, instead of foo being "____blah" (with 4 spaces at the start), it's just "blah". Why doesn't PadLeft do what I expect?

+3  A: 

Because the first argument is total length of resulting string and not number of character to pad. So in your example you want to use 8 instead of 4.

Brian Rasmussen
Uh, ok.... That's odd behavior, at least to me... Thanks for the help :)
RCIX
@RCIX: It is quite smart behavior, since the most common use for pad is to create a fix length string and then it is very simple to use, no need to calculate the length yourself.
Albin Sunnanbo
@Albin Sunnanbo: Thanks, couldn't have said it better myself.
Brian Rasmussen
+2  A: 

The first argument to PadLeft specifies the total resulting length you want. Since "blah" starts out four characters long, no padding is added when you specify a length of four. If you want to insert four spaces, change your call to string foo = "blah".PadLft(8, ' '); Since the default padding character is a space, you can skip specifying that and just use string foo = "blah".PadLeft(8)

Jerry Coffin