I needed a one-liner to convert a string to an integer, and if the string is anything invalid, then just set it to zero. So I made the following extension method, but I can imagine there is a system method to do this in one line.
Is there another way to do this in one line without creating an extension method?
using System;
namespace TestForceInteger
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("testing".ForceInteger() + 1);
Console.WriteLine("199".ForceInteger() + 1);
int test = StringHelpers.ForceInteger(null);
Console.WriteLine(test + 1);
Console.ReadLine();
//output:
//1
//200
//1
}
}
public static class StringHelpers
{
public static int ForceInteger(this string potentialInteger)
{
int result;
if (int.TryParse(potentialInteger, out result))
return result;
else
return 0;
}
}
}