2

when I write

(int)dataTable1.Rows[0]["field1"] 

I get an error that this is an invalid cast.
The value in "field1" is "20"

when I do this

int.parse(dataTable1.Rows[0]["field1"].ToString())

it works.

But why can (int)dataTable1.Rows[0]["field1"] not be casted to an int when the value is "20".
What is the difference with int.parse ?

GuidoG
  • 11,359
  • 6
  • 44
  • 79
  • So if I understand it right in @Sklivvz answer of the duplicate, casting like (int)object means threat the object as if it where an int. And because "20" is a string not an int, it will fail. Is this correct ? – GuidoG Aug 30 '17 at 15:28
  • Basically, yes. There's no direct cast from a string to an integer. But a string can potentially be *parsed* to an integer. I haven't actually seen the source code for `int.Parse()`, but I'd wager it's doing something other than casting. – David Aug 30 '17 at 15:31

0 Answers0