locked
Difference between (string)dr["Data"] and dr["Data"].ToString() RRS feed

  • Question

  • User320184449 posted

    I'm a VB developer finally learning C# and I'm wondering if there's a difference between (string)dr["Data"] and dr["Data"].ToString() or (int)dr["Data"] and Convert.ToInt32(dr["Data"]), anyone out there know? I'm in the middle of converting a huge VB project and I'm not sure which one to use.

    Monday, November 16, 2020 11:46 AM

Answers

  • User-821857111 posted

    When you use casting e.g. (string)myObject, the type represented by myObject must be the same as the one you are casting to. So if myObject is actually a number or datetime, the casting will fail with an InvalidCastException. 

    You use Convert.ToInt32 to convert a string or object to an int. You get a FormatException if the type to be converted cannot be converted to a number. You can use casting again, if you are certain that the underlying type is an int. 

    You can call ToString() on anything without any fear of exceptions.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 16, 2020 12:34 PM