What's the best way to do the equivalent of int.TryParse (which is found in .net 2.0 onwards) using .net 1.1.
            Asked
            
        
        
            Active
            
        
            Viewed 4,393 times
        
    4 Answers
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
- 
                    Might want to `return True` somewhere in that? – Pondidum Feb 25 '11 at 15:07
- 
                    @Pondidum: Good call! Thanks. – Anton Gogolev Feb 26 '11 at 20:13
3
            
            
        try
{
    var i = int.Parse(value);
}
catch(FormatException ex)
{
    Console.WriteLine("Invalid format.");
}
 
    
    
        Konstantin Tarkus
        
- 37,618
- 14
- 135
- 121
- 
                    1Doesn't the exception throwing/handling create a fair bit of overhead though? – Matthew Dresser Apr 02 '09 at 11:33
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
 
    
    
        Jamie Bruce
        
- 11
- 2
