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

后端 未结 12 1635
星月不相逢
星月不相逢 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 03:57

    There is not a default cast from string to int in .NET. You can use int.Parse() or int.TryParse() to do this. Or, as you have done, you can use Convert.ToInt32().

    However, in your example, why do a ToString() and then convert it back to an int at all? You could simply store the int in Session and retrieve it as follows:

    int i = Session["name1"];
    

提交回复
热议问题