#1,192 – Following the TryParse Pattern
September 29, 2014 3 Comments
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; } }
Pingback: Dew Drop – September 29, 2014 (#1865) | Morning Dew
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)`
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.