开发者

C# program,with tostring() or not,which is better

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; bu开发者_如何学Ct 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?


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜