Lance's Whiteboard

Random scribbling about C#, Javascript, Web Development, Architecture, and anything else that pops into my mind.

News


Creative Commons License
Lance's Whiteboard Blog by Lance Hunt is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.
Based on a work at weblogs.asp.net




Sponsored Ad
Sponsored Ad

Blogs I Read

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:

    int testNumber = 12345;
    
string myString = testNumber.ToString("00000000");
 
And you can do even greater things with:
 
    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:

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.

Comments

Drew Marsh said:

I have a personal rule where if I start to write a piece of code and it seems like something I'll be able to to reuse myself, I'll stop writing and go do a quick Google to make sure I'm not wasting my time writing something that the framework either supplies for me or someone has already spent time writing. :)
# March 18, 2004 6:29 PM