Kiran Mohanty
What is the difference between int.TryParse() & Convert.ToInt32() in C#?

Convert.ToInt32():- converts a string to an integer value if value of the string has a valid number, else it throws an exception.

Ex:-
Convert.ToInt32(“12”); // output -12
Convert.ToInt32(“12ewfshg”); // runtime exception*

int.TryParse()- tries to convert a string to integer. If it’s value is not a valid integer , it initialize out value to 0 and the expression returns false.

Ex:-
int result;
int.TryParse(“12”,out result); // expression returns a boolean value of true and result = 12;
int.TryParse(“12ewfs”,out result); // expression returns a boolean value of false and result = 0;*

By Kiran Mohanty in .NET on Aug 29 2020
  • Logesh Palani
    Sep, 2020 7

    Convert.Int32 does not through exception , when you pass parameter as null. but, Int.Parse does through exception.

    • 2
  • Santhosh Kumar
    Sep, 2020 9

    • 0
  • Kiran Mohanty
    Sep, 2020 8

    My earlier comment has a typo…
    Both Convert.ToInt32 & int.TryParse will return 0 while converting null. Only int.Parse of null will throw an exception.

    • 0
  • Kiran Mohanty
    Sep, 2020 8

    Both Convert.ToInt32 & Int.Parse will return 0 while converting null.

    • 0

Most Popular Job Functions


MOST LIKED QUESTIONS