Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net-1.1

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

like image 601
Matthew Dresser Avatar asked Apr 02 '09 11:04

Matthew Dresser


People also ask

What is difference between Parse and TryParse?

The Parse method returns the converted number; the TryParse method returns a boolean value that indicates whether the conversion succeeded, and returns the converted number in an out parameter. If the string isn't in a valid format, Parse throws an exception, but TryParse returns false .

What is the difference between int parse and int TryParse?

TryParse method returns false i.e. a Boolean value, whereas int. Parse returns an exception.

Why do we use TryParse in C#?

TryParse(String, NumberStyles, IFormatProvider, Int32) Converts the string representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.


1 Answers

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;
        }
    }
}
like image 93
Anton Gogolev Avatar answered Sep 23 '22 04:09

Anton Gogolev