What's the main difference between int.Parse() and Convert.ToInt32

前端 未结 13 2287
-上瘾入骨i
-上瘾入骨i 2020-11-22 08:47
  • What is the main difference between int.Parse() and Convert.ToInt32()?
  • Which one is to be preferred
13条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 08:55

    • If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use Int32.Parse().

    • If you're collecting input from a user, you'd generally use Int32.TryParse(), since it allows you more fine-grained control over the situation when the user enters invalid input.

    • Convert.ToInt32() takes an object as its argument. (See Chris S's answer for how it works)

      Convert.ToInt32() also does not throw ArgumentNullException when its argument is null the way Int32.Parse() does. That also means that Convert.ToInt32() is probably a wee bit slower than Int32.Parse(), though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.

提交回复
热议问题