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

后端 未结 12 1586
星月不相逢
星月不相逢 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:50

    This is already discussed but I want to share a dotnetfiddle.

    If you are dealing with arithmetic operations and using float, decimal, double and so on, you should better use Convert.ToInt32().

    using System;
    
    public class Program
    {
      public static void Main()
      {
        double cost = 49.501;
        Console.WriteLine(Convert.ToInt32(cost));
        Console.WriteLine((int)cost);
      }
    }
    

    Output

    50
    49
    

    https://dotnetfiddle.net/m3ddDQ

提交回复
热议问题