Advertisement
Guest User

Untitled

a guest
Oct 20th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. using System;
  2. class Program
  3. {
  4. static void Main(string[] args)
  5. {
  6. int sum;
  7.  
  8. Console.WriteLine("\n1. Using Convert.ToInt32() without exception handling.");
  9. sum = 0;
  10. foreach (string arg in args)
  11. {
  12. int intValue = Convert.ToInt32(arg); // arg string may not parse to an int!
  13. sum += intValue;
  14. }
  15. Console.WriteLine(sum);
  16.  
  17. Console.WriteLine("\n2. Using Convert.ToInt32() with exception handling.");
  18. sum = 0;
  19. foreach (string arg in args)
  20. {
  21. try
  22. {
  23. int intValue = Convert.ToInt32(arg); // arg string may not parse to an int!
  24. sum += intValue;
  25. }
  26. catch
  27. {
  28. Console.WriteLine("arg " + arg + " could not be parsed to an int");
  29. }
  30. }
  31. Console.WriteLine(sum);
  32.  
  33. Console.WriteLine("\n3. Using int.Parse() without exception handling.");
  34. sum = 0;
  35. foreach (string arg in args)
  36. {
  37. int intValue;
  38. intValue = int.Parse(arg);
  39. {
  40. sum += intValue;
  41. }
  42. }
  43. Console.WriteLine(sum);
  44.  
  45. Console.WriteLine("\n4. Using int.Parse() with exception handling.");
  46. sum = 0;
  47. foreach (string arg in args)
  48. {
  49. int intValue;
  50. try
  51. {
  52. intValue = int.Parse(arg);
  53. {
  54. sum += intValue;
  55. }
  56. }
  57. catch
  58. {
  59. Console.WriteLine("arg " + arg + " could not be parsed to an int");
  60. }
  61. }
  62. Console.WriteLine(sum);
  63.  
  64.  
  65. Console.WriteLine("\n5. Using int.TryParse() so no exception handling required!");
  66. sum = 0;
  67. foreach (string arg in args)
  68. {
  69. int intValue;
  70. if (int.TryParse(arg, out intValue))
  71. {
  72. sum += intValue;
  73. }
  74. }
  75. Console.WriteLine(sum);
  76. }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement