Author Topic: string declaration  (Read 712 times)

babu

  • Newbie
  • *
  • Posts: 1
  • Karma: +0/-0
    • View Profile
string declaration
« on: December 03, 2015, 01:48:32 AM »
Hi thank for your effort very useful.

What is the difference in declaring string.

val = val + (string)dataGridView1.Rows.Cells[0].Value + "\n"

val = val + dataGridView1.Rows.Cells[0].Value.ToString() + "\n"

mkaatr

  • Administrator
  • Full Member
  • *****
  • Posts: 115
  • Karma: +1/-0
    • View Profile
Re: string declaration
« Reply #1 on: February 21, 2016, 01:45:06 PM »
val = val + (string)dataGridView1.Rows.Cells[0].Value + "\n"

The above statement casts the object returned from the cell to a string. So this might trigger an error. For example if the cell's content is a number or an image, then you get an exception.

as for val = val + dataGridView1.Rows.Cells[0].Value.ToString() + "\n"

If the cell contains a number, it will be converted to a string, and no exception will happen. I am not sure if it was an image it will be converted to a string. In a nutshell this technique prevents some of the exceptions that might happen in the first statement.

yours sincerely