What is the main difference between int.Parse() and Convert.ToInt32 in C#?

CsharpServer Side ProgrammingProgramming

Convert a string representation of number to an integer, using the int.Parse or Convert.ToInt32 method in C#. If the string cannot be converted, then the int.Parse or Convert.ToInt32 method returns an exception

Convert.ToInt32 allows null value, it doesn't throw any errors Int.parse does not allow null value, and it throws an ArgumentNullException error.

Example

 Live Demo

class Program {
   static void Main() {
      int res;
      string myStr = "5000";
      res = int.Parse(myStr);
      Console.WriteLine("Converting String is a numeric representation: " + res);
      Console.ReadLine();
   }
}

Output

Converting String is a numeric representation: 5000

Example

 Live Demo

class Program {
   static void Main() {
      int res;
      string myStr = null;
      res = Convert.ToInt32(myStr);
      Console.WriteLine("Converting String is a numeric representation: " + res);
      Console.ReadLine();
   }
}

Output

Converting String is a numeric representation: 0

Example

 Live Demo

class Program {
   static void Main() {
      int res;
      string myStr = null;
      res = int.Parse(myStr);
      Console.WriteLine("Converting String is a numeric representation: " + res);
      Console.ReadLine();
   }
}

Output

Unhandled exception. System.ArgumentNullException: Value cannot be null.
raja
Published on 08-Aug-2020 11:13:29
Advertisements