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

Viewed 77924

The following code throws an compile-time error like

Cannot convert type 'string' to 'int'

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

whereas the code below compiles and executes successfully:

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

I would like to know:

  1. Why does the the first code generate a compile-time error?

  2. What's the difference between the 2 code snippets?

12 Answers

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

Related