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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

3 Responses to #1,192 – Following the TryParse Pattern

  1. Pingback: Dew Drop – September 29, 2014 (#1865) | Morning Dew

  2. Please don’t encourage people to do this. This is a solved problem, other languages have solved it with the maybe monad. You can even achieve it in c# using nullable types (though I would recommend creating your own maybe class.

    Using out parameters not only requires awkward syntax where you initialize a variable but don’t assign to it, but is also not chain-able. With maybe monads you can do something like `dog.Bark().IfSuccess(sound => Console.WriteLine(sound))`. Heck, I commonly use this with an IfNotNull extension method `getSomeValue().IfNotNull(val => val.Foo)`

  3. Steven says:

    George – I think Sean just wanted to point out the concept of try and not try. Try is implicit conversion. Not try is explicit. Ex: int.TryParse vs. int.Parse. TryParse returns true/false whereas Parse throws an exception if parse is not successful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: