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.
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.
Member
139 Points
344 Posts
Difference between (string)dr["Data"] and dr["Data"].ToString()
Nov 16, 2020 11:46 AM|GuyCre8ive|LINK
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.
All-Star
194524 Points
28081 Posts
Moderator
Re: Difference between (string)dr["Data"] and dr["Data"].ToString()
Nov 16, 2020 12:34 PM|Mikesdotnetting|LINK
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.