Skip to content

Instantly share code, notes, and snippets.

@peterthorsteinson
Created October 2, 2019 13:19
Show Gist options
  • Select an option

  • Save peterthorsteinson/940d698e4d16775bdca13ea1334f0b4d to your computer and use it in GitHub Desktop.

Select an option

Save peterthorsteinson/940d698e4d16775bdca13ea1334f0b4d to your computer and use it in GitHub Desktop.
using System;
class Program
{
static void Main(string[] args)
{
int sum;
Console.WriteLine("\n1. Using Convert.ToInt32() without exception handling.");
sum = 0;
foreach (string arg in args)
{
int intValue = Convert.ToInt32(arg); // arg string may not parse to an int!
sum += intValue;
}
Console.WriteLine(sum);
Console.WriteLine("\n2. Using Convert.ToInt32() with exception handling.");
sum = 0;
foreach (string arg in args)
{
try
{
int intValue = Convert.ToInt32(arg); // arg string may not parse to an int!
sum += intValue;
}
catch
{
Console.WriteLine("arg " + arg + " could not be parsed to an int");
}
}
Console.WriteLine(sum);
Console.WriteLine("\n3. Using int.Parse() without exception handling.");
sum = 0;
foreach (string arg in args)
{
int intValue;
intValue = int.Parse(arg);
{
sum += intValue;
}
}
Console.WriteLine(sum);
Console.WriteLine("\n4. Using int.Parse() with exception handling.");
sum = 0;
foreach (string arg in args)
{
int intValue;
try
{
intValue = int.Parse(arg);
{
sum += intValue;
}
}
catch
{
Console.WriteLine("arg " + arg + " could not be parsed to an int");
}
}
Console.WriteLine(sum);
Console.WriteLine("\n5. Using int.TryParse() so no exception handling required!");
sum = 0;
foreach (string arg in args)
{
int intValue;
if (int.TryParse(arg, out intValue))
{
sum += intValue;
}
}
Console.WriteLine(sum);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment