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.

[351 byte] By [ChuaWenChing] at [2008-2-11]
# 1
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?

AaronAnderson at 2007-8-21 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 2
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.

DavidM.Kean at 2007-8-21 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 3
Thanks for the replies.

Now i understand. One more question.

Is (int) same with Int32.Parse? So underneath of (int) is Int32.Parse?

Thanks.

ChuaWenChing at 2007-8-21 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 4
Doh!

It does help to be looking at the right method in Reflector.Tongue Tied

AaronAnderson at 2007-8-21 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 5
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.

DavidM.Kean at 2007-8-21 > top of Msdn Tech,.NET Development,.NET Base Class Library...
# 6
David,

Thanks a lot. I understand now.

Cheers.

ChuaWenChing at 2007-8-21 > top of Msdn Tech,.NET Development,.NET Base Class Library...

.NET Development

Site Classified