Skip to main content
Fix typo and do some small improvements
Source Link
Misha Zaslavsky
  • 9.9k
  • 12
  • 87
  • 125

All the above answers are good but for information, we can use int.TryParse which is safe to convert string to int  , for example

// TryParse returns true if the conversion succeeded // and stores the result in j. int j; if (Int32.TryParse("-105", out j)) Console.WriteLine(j); else Console.WriteLine("String could not be parsed."); // Output: -105 

TryParse never throws an exception—even on invalid input and null. It is overall preferable to int.Parseint.Parse in most program contexts.

Source: How to convert string to int in C#? (With Difference between Int.Parse and Int.TryParse)

All above answers are good but for information, we can use int.TryParse which is safe to convert string to int  , example

// TryParse returns true if the conversion succeeded // and stores the result in j. int j; if (Int32.TryParse("-105", out j)) Console.WriteLine(j); else Console.WriteLine("String could not be parsed."); // Output: -105 

TryParse never throws an exception—even on invalid input and null. It is overall preferable to int.Parse in most program contexts.

Source: How to convert string to int in C#? (With Difference between Int.Parse and Int.TryParse)

All the above answers are good but for information, we can use int.TryParse which is safe to convert string to int, for example

// TryParse returns true if the conversion succeeded // and stores the result in j. int j; if (Int32.TryParse("-105", out j)) Console.WriteLine(j); else Console.WriteLine("String could not be parsed."); // Output: -105 

TryParse never throws an exception—even on invalid input and null. It is overall preferable to int.Parse in most program contexts.

Source: How to convert string to int in C#? (With Difference between Int.Parse and Int.TryParse)

Source Link
Vikas Lalwani
  • 1.1k
  • 19
  • 34

All above answers are good but for information, we can use int.TryParse which is safe to convert string to int , example

// TryParse returns true if the conversion succeeded // and stores the result in j. int j; if (Int32.TryParse("-105", out j)) Console.WriteLine(j); else Console.WriteLine("String could not be parsed."); // Output: -105 

TryParse never throws an exception—even on invalid input and null. It is overall preferable to int.Parse in most program contexts.

Source: How to convert string to int in C#? (With Difference between Int.Parse and Int.TryParse)