2

If x is a value then are the following just syntactically different but effectively the same? Is the second a shortcut for the first?

Convert.ToInt32(x);
(int)x;

Or can one be used in some circumstances over and above the other?

Looking in MSDN it seems that the first is doing something different to the second.

whytheq
  • 34,466
  • 65
  • 172
  • 267

6 Answers6

3

(int) is explicit cast where Convert.ToInt is method

Consider:

string x = "1";
int temp = 0;
temp = Convert.ToInt32(x);
temp = (int)x; //This will give compiler error

Casting works for compatible types:

long l = 123;
int temp2 = (int)l;

double d = 123.2d;
int temp3 = (int)d; // holds only the int part 123

You may see Explicit cast - MSDN

if a conversion cannot be made without a risk of losing information, the compiler requires that you perform an explicit conversion, which is called a cast. A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might occur.

Habib
  • 219,104
  • 29
  • 407
  • 436
2

In addition to all the other posts here, that Convert.ToInt32 tends to round result, whilst int, truncates it.

Example:

  float x = -0.6f;
  var b = Convert.ToInt32(x);
  var r = (int)x;

The result of this is that b==-1, bur r==0.

This is fundamental difference to remember

winwaed
  • 7,645
  • 6
  • 36
  • 81
Tigran
  • 61,654
  • 8
  • 86
  • 123
1

If x is a string containing a number, the first one will succeed but the second one will fail.

object x = "1";
Convert.ToInt32(x); // works
(int)x; // fails
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
1

Convert.ToInt32 is a method, which converts many types of objects to int, and (int) is simple casting - which may lead to exceptions

JleruOHeP
  • 10,106
  • 3
  • 45
  • 71
1

They are different. int is a casting, ToInt32 is a conversion process. It does much more, is more tolerant of incorrect data, and pretty much always works.

Jordan
  • 31,971
  • 6
  • 56
  • 67
1

For (int)x , built into the CLR and requires that x be a numeric variable otherwise will give an exception.

Convert.ToInt32 is designed to be a general conversion function which convert from any primitive type to a int.

Vishal Suthar
  • 17,013
  • 3
  • 59
  • 105