3

a C# program, as you see , var month is defined as int, someone said without .tostring() is better, it should remove redundant call, now it is:str= "0" + Month; but i think it's not good .which one is better? why? thanks!(ps:my first question in stackoverflow)

string strM = string.Empty;
if ( Month < 10 )
    strM = "0" + Month.ToString ( );
    //strM = "0" + Month; which is better?

3 Answers 3

8

Use string format instead:

string strM = string.Format("{0:00}", Month);

Test:

Month: 1 => strM: "01"
Month: 12 => strM: "12"

For more string format tips check this.

1
  • thank you ,but i think Month.ToString("00") is better,it needn't call Class string Aug 10, 2011 at 8:33
1

The best way is to use .tostring, but not as shown.

    using System;
    class example {
        static void Main(string[] args) {
            int Month =5;
            Console.WriteLine(Month.ToString("00"));
        }
    }

http://ideone.com/LCwca

Outputs: 05

0

As for your question other part, there is no difference, only clarity (style) of the code. Which to use it up to you. If you want to make an accent on that Month is not a string then you can add .ToString(). If this is obvious, like with if ( Month < 10 ), so you can see one line above comparison with int, hence Month is definetely not a string you can omit .ToString() call since it will be done automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.