Difference between (int), Int32.Parse and Convert.ToInt32?
Hi,
I have been wondering. In which scenario, I should be using (int), Int32.Parse and Convert.ToInt32?
Or are they the same? I do notice in certain condition that i cannot cast directly using (int) and I have to use Convert.ToInt32.
I am not that sure why i do that. I just need some confirmations from you all.
Thank you.
Cheers.
Good question.
Oddly enough, it appears that Convert.ToInt32() has a completely different stack trace than Int32.Parse().
I wonder why the implementation is different?
Basically the Convert class makes it easier to convert between all the base types.
The Convert.ToInt32(String, IFormatProvider) underneath calls the Int32.Parse. So the only difference is that if a null string is passed to Convert it returns 0, whereas Int32.Parse throws an ArgumentNullException.
It is really a matter of choice whichever you use.
Also have a look at the new .NET 2.0 method Int32.TryParse, which attempts to convert a string to an int without throwing an exception.
Chua Wen Ching wrote: |
| Thanks for the replies. Now i understand. One more question. Is (int) same with Int32.Parse? So underneath of (int) is Int32.Parse? Thanks. |
|
No. (int) will only convert types that can be represented as an integer (ie double, long, float, etc) although some data loss may occur.
Int32.Parse will only convert strings to integers. You can't cast (ie (int)mystring) strings to integers.