Local variables or direct statements?

前端 未结 7 1536
旧时难觅i
旧时难觅i 2021-01-25 23:55

I am currently studying C# and I really want to get a good coding style from the beginning, so I would like to hear opinions from you professionals on this matter.

Shoul

7条回答
  •  北海茫月
    2021-01-26 00:23

    I suggest you use a local variable like here:

    bool parseSuccess = double.TryParse(stringToParse, out dblValue);
    if (parseSuccess) ...
    

    For two reasons:

    1. You can use more times the variable without parse your double another time.

    2. It makes the code more readable.

    Consider this:

    if(double.TryParse(string1, out Value1) && double.TryParse(string2, out Value2) && double.TryParse(string3, out Value3) && double.TryParse(string4, out Value4))
    {
        //some stuff
    }
    

    It's too long and it makes the code hard to be read. So sometimes local variabels make the code a lot more readable.

提交回复
热议问题