To build on musefan's answer, I like the same pattern but with a generic Result type so I can use it throughout the whole codebase:
public class Result
{
public bool Success { get; set; }
public string ErrorMessage { get; set; }
}
public class Result : Result
{
public T Data;
}
One reason I like this vs. throwing an exception out of a function that otherwise returns data, is that this helps you map that function over a collection, capturing exception details in error messages, so you don't have to worry about an exception on one item blowing up the whole chain. This is good for situations like parsing lines out of a flat data file, where successful lines should move forward but any errors should be dealt with individually:
public static Result ParseThing(string line)
{
try
{
// Parse a Thing (or return a parsing error.)
return new Result { Data = thing, Success = true };
}
catch (Exception ex)
{
return new Result { Data = null, Success = false, ErrorMessage = "..." };
}
}
...
var results = lines.Select(ParseThing);
foreach (var result in results)
{
// Check result.Success and deal with successes/failures here.
}
Of course, you still have the option of throwing an exception out of that function for truly exceptional situations when blowing up the whole chain of processing is what you want.
P.S. Every day is the day I wish C# had multiple return values.