What's the best alternative to int.TryParse for .net 1.1
Asked Answered
A

4

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.

Ardenia answered 2/4, 2009 at 11:29 Comment(0)
S
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;
        }
    }
}
Swanskin answered 2/4, 2009 at 11:33 Comment(2)
Might want to return True somewhere in that?Ramsey
@Pondidum: Good call! Thanks.Swanskin
M
3
try
{
    var i = int.Parse(value);
}
catch(FormatException ex)
{
    Console.WriteLine("Invalid format.");
}
Mongrel answered 2/4, 2009 at 11:31 Comment(1)
Doesn't the exception throwing/handling create a fair bit of overhead though?Ardenia
U
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.");
}
Unfurl answered 19/10, 2010 at 14:9 Comment(0)
W
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;
    }
}
Weatherbeaten answered 20/6, 2011 at 9:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.