tags:

views:

630

answers:

3

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

+2  A: 
try
{
    var i = int.Parse(value);
}
catch(FormatException ex)
{
    Console.WriteLine("Invalid format.");
}
Koistya Navin
Doesn't the exception throwing/handling create a fair bit of overhead though?
mdresser
+8  A: 

Obviously,

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

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

        catch(OverflowException)
        {
            return false;
        }
    }
}
Anton Gogolev
+1  A: 

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.");
}
ray023