#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;
        }
    }
Advertisement