8

What's the best way to do the equivalent of int.TryParse (which is found in .net 2.0 onwards) using .net 1.1.

Matthew Dresser
  • 11,273
  • 11
  • 76
  • 120

4 Answers4

12

Obviously,

class Int32Util
{
    public static bool TryParse(string value, out int result)
    {
        result = 0;

        try
        {
            result = Int32.Parse(value);
            return true;
        }
        catch(FormatException)
        {            
            return false;
        }

        catch(OverflowException)
        {
            return false;
        }
    }
}
Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
3
try
{
    var i = int.Parse(value);
}
catch(FormatException ex)
{
    Console.WriteLine("Invalid format.");
}
Konstantin Tarkus
  • 37,618
  • 14
  • 135
  • 121
1

Koistya almost had it. No var command in .NET 1.1.

If I may be so bold:

try
{
    int i = int.Parse(value);
}
catch(FormatException ex)
{
    Console.WriteLine("Invalid format.");
}
ray
  • 8,521
  • 7
  • 44
  • 58
1

There is a tryparse for double, so if you use that, choose the "NumberStyles.Integer" option and check that the resulting double is within the boundaries of Int32, you can determine if you string is an integer without throwing an exception.

hope this helps, jamie

private bool TryIntParse(string txt)
{
    try
    {
        double dblOut = 0;
        if (double.TryParse(txt, System.Globalization.NumberStyles.Integer
        , System.Globalization.CultureInfo.CurrentCulture, out dblOut))
        {
            // determined its an int, now check if its within the Int32 max min
            return dblOut > Int32.MinValue && dblOut < Int32.MaxValue;
        }
        else
        {
            return false;
        }
    }
    catch(Exception ex)
    {
        throw ex;
    }
}
Darren
  • 68,902
  • 24
  • 138
  • 144