String Formatting
I constantly see people write code like this for formatting numbers as strings, and wonder why:
int testNumber = 12345;
string myString = testNumber.ToString();
for(int i=0; i< 8 - myString.Length; i++)
{
myString = "0" + myString;
}
Especially when this is much easier:
And you can do even greater things with:int testNumber = 12345;
string myString = testNumber.ToString("00000000");
String.Format(myFormatString, args[]);
I think a lot of this comes from people (like me) who came from VB6 and other primitive languages that didnt have String Formatting features built-in. Here are some links I frequently suggest for those interesting in learning:
- Formatting Overview
- Composite Formatting
- Standard Numeric Format Strings
- Custom Numeric Format Strings
- Customizing Format Strings
Moral of the story; The .NET Framework gives developers alot of tools to do your job. If you ever start thinking, "Gosh, this should be wrapped in the framework", you will likely find that it already is. Obviously, I left-out another option; Regular Expressions, but that discussion is left for a day with more time.