Search code examples
c#string.format

Format string without string.Format?


I added a variable of type int and I used it to call something like:

x.ToString("0000");

I changed x to type string and now the above is invalid. Is the only way to format x now:

string.Format("{0:0000}",x);

or is there a short-cut?

I am using StringBuilder to build the string, so does the same apply for AppendFormat?


Solution

  • No real shortcut.

    Int32 doesn't have a concept of how many leading zeros the int should have.

    You're doing the correct thing by formatting to string. If you're using that to display stuff, it shouldn't really be an issue ( you still have x if you want to perform numeric operations ).

    AppendFormat works like string.Format, but appends to the StringBuilder object it is called on.