Kishore Kumar
Kishore Kumar

Reputation: 21863

Which conversion method is better?

Convert.ToInt32 or Int.Parse which is better and why? Is there any specific condition where i can use these two?.

Upvotes: 2

Views: 176

Answers (5)

Tullo_x86
Tullo_x86

Reputation: 2673

If you don't expect null to ever be passed as the argument, use int.Parse, since then you'll be alerted via an exception when something does go wrong.

Upvotes: 0

David Lynch
David Lynch

Reputation: 1716

From Reflector:

public static int ToInt32(string value)
{
    if (value == null)
    {
        return 0;
    }
    return int.Parse(value, CultureInfo.CurrentCulture);
}

So calling int.Parse() would be a little quicker.

Upvotes: 0

Kangkan
Kangkan

Reputation: 15571

Convert.ToInt32 internally calls Int.Parse with a null check. So the Null check is extra and does not throw in case of a Null parameter.

You can refer to this question here: Any performance difference between int.Parse() and Convert.Toint()?

Upvotes: 2

Rex M
Rex M

Reputation: 144112

Presumably you're asking about the Convert.ToInt32 which takes a string. In that case, it simply calls int.Parse internally, so there's no real difference except that Convert gracefully handles null by returning 0.

Upvotes: 7

JSBձոգչ
JSBձոգչ

Reputation: 41378

One of them calls the other (though I can't remember which is which ATM), so there's no practical difference between them.

Upvotes: 1

Related Questions