This has been an irritating method to use especially when you don’t use it too often. Here are some tips about using PadLeft() and PadRight().

First off it is not a static method, you need an instance of a string in order to use it.
Secondly keep in mind that these methods are poorly named, they don’t actually pad anything unless you specify how much you want to pad plus the size of the current string that you want to pad. I think that is rather stupid. No really, what is the point of that method if it doesn’t implicitly use the size of the current string? I must be missing something.

Usage if you are trying to actually place spaces next to (either side) of the string in question

string strTarget = "content";

strTarget.PadLeft(strTarget.Length + 7);  //Result: "       content" 
strTarget.PadRight(strTarget.Length + 7); //Result: "content       "

If you didn’t specify the string’s length then you would not see any padding. This is an irritating gotcha.

Leave a Reply

Your email address will not be published. Required fields are marked *