#1,192 – Following the TryParse Pattern

The int.TryParse method does the same thing as the int.Parse method, but without throwing an exception.  Instead, it returns a boolean value indicating whether the method succeeded or not and writes the result to an out parameter.

You might follow the same pattern when writing your own code, providing a method that throws an exception on failure and a TryXxx version of the method that returns a boolean indicating whether the method succeeded.  Below is an example.

    public class Dog
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public Dog(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public bool TryBark(out string barkSound)
        {
            bool success = false;
            barkSound = "";

            if (Age <= 10)
            {
                success = true;
                barkSound = "Woof";
            }

            return success;
        }

        public string Bark()
        {
            string barkSound;

            if (!TryBark(out barkSound))
                throw new Exception("This dog can't bark");
            return barkSound;
        }
    }
Advertisements

#1,011 – TryParse Indicates Whether a Parse Operation Will Succeed

You can use the Parse method to convert a string that represents a number to its equivalent numerical representation.

            string numberString = "108";
            int number = int.Parse(numberString);

If the string does not represent a value of the associated numeric type, or represents a numeric value that is outside the range of the type, a FormatException or OverflowException is generated.

            int n1 = int.Parse("3.4");    // FormatException

You can avoid the exception by using the TryParse method.  If the parse operation succeeds, the parsed value is stored in the output parameter and TryParse returns true.  If the parse operation does not succeed, the output parameter is not written to and TryParse returns false.  No exception is thrown.

            int n1;
            if (int.TryParse("3.4", out n1))
                Console.WriteLine("Parse worked--n1 contains number");
            else
                Console.WriteLine("Can't parse");

1011-001