C# Int32.TryParse Method


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. using System;
  2.  
  3. public class StringParsing
  4. {
  5. public static void Main()
  6. {
  7. TryToParse(null);
  8. TryToParse("160519");
  9. TryToParse("9432.0");
  10. TryToParse("16,667");
  11. TryToParse(" -322 ");
  12. TryToParse("+4302");
  13. TryToParse("(100);");
  14. TryToParse("01FA");
  15. }
  16.  
  17. private static void TryToParse(string value)
  18. {
  19. int number;
  20. bool result = Int32.TryParse(value, out number);
  21. if (result)
  22. {
  23. Console.WriteLine("Converted '{0}' to {1}.", value, number);
  24. }
  25. else
  26. {
  27. if (value == null) value = "";
  28. Console.WriteLine("Attempted conversion of '{0}' failed.", value);
  29. }
  30. }
  31. }
  32. // The example displays the following output to the console:
  33. // Attempted conversion of '' failed.
  34. // Converted '160519' to 160519.
  35. // Attempted conversion of '9432.0' failed.
  36. // Attempted conversion of '16,667' failed.
  37. // Converted ' -322 ' to -322.
  38. // Converted '+4302' to 4302.
  39. // Attempted conversion of '(100);' failed.
  40. // Attempted conversion of '01FA' failed.

URL: http://msdn.microsoft.com/en-us/library/f02979c7.aspx

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.