What is the difference between Convert.ToInt32 and (int)?

后端 未结 12 1608
星月不相逢
星月不相逢 2020-11-27 03:11

The following code throws an compile-time error like

Cannot convert type \'string\' to \'int\'

string name = Session[\"name1\"].ToString();
int i = (         


        
12条回答
  •  再見小時候
    2020-11-27 04:00

    (this line relates to a question that was merged) You should never use (int)someString - that will never work (and the compiler won't let you).

    However, int int.Parse(string) and bool int.TryParse(string, out int) (and their various overloads) are fair game.

    Personally, I mainly only use Convert when I'm dealing with reflection, so for me the choice is Parse and TryParse. The first is when I expect the value to be a valid integer, and want it to throw an exception otherwise. The second is when I want to check if it is a valid integer - I can then decide what to do when it is/isn't.

提交回复
热议问题