How to convert a string to an integer in c#?

Converting a string representation of a number to an integer type is a common task.

Example:


  string numberStr = "123";
  int number = Convert.ToInt32(numberStr);
  

Solution:

You can also use int.Parse or int.TryParse for more control over error handling:


  if(int.TryParse(numberStr, out int parsedNumber))
  {
      Console.WriteLine(parsedNumber);
  }
  else
  {
      Console.WriteLine("Invalid number format.");
  }
  

Beginner's Guide to C#