0

Possible Duplicate:
difference between Convert.ToInt32 and (int)

What it difference between (int) and convert.toint() methods?

like

object o = 123;
int i = (int)o;
and
int i = Convert.ToInt16(o);

What is the difference in both of them?

Community
  • 1
  • 1
Gaurav Agrawal
  • 4,355
  • 10
  • 42
  • 61

2 Answers2

1

The first method is (Un)Boxing the second method is conversion

DaveShaw
  • 52,123
  • 16
  • 112
  • 141
0

You can convert another type to an int but to cast to an int it needs to be a boxed int.

e.g.:

string s = "123";
int i = Convert.ToInt16(s);

or

object o = 123;
int i = (int)o;

works fine. However:

string s = "123";
int i = (int)s;

won't compile.

Ben Robinson
  • 21,601
  • 5
  • 62
  • 79
  • my question is difference between casting and converting? – Gaurav Agrawal Jun 21 '11 at 10:28
  • The difference is that casting to an int, you are simply unboxing an int, if it is not an int then it fails at run time. With converting it can be a string or anything that has a valid conversion to int. – Ben Robinson Jun 21 '11 at 10:32