2 possibilities spring to mind
- Use the TryXXX pattern (used in some BCL methods such as DateTime.TryParse).
- Design a class that contains the status of the operation and the result and then have your method return this class.
Let's first see the TryXXX pattern. It's basically a method that returns a boolean value and the result as out
parameter.
public bool TryXXX(string someInput, out string someResult, out string errorMessage)
{
...
}
which will be consumed like this:
string someResult;
string errorMessage;
if (!TryXXX("some parameter", out someResult, out errorMessage))
{
// an error occurred => use errorMessage to get more details
}
else
{
// everything went fine => use the results here
}
In the second approach you would simply design a class that will contain all the necessary information:
public class MyResult
{
public bool Success { get; set; }
public string ErrorMessage { get; set; }
public string SomeResult { get; set; }
}
and then have your method return this class:
public MyResult MyMethod(string someParameter)
{
...
}
which will be consumed like this:
MyResult result = MyMethod("someParameter");
if (!result.Success)
{
// an error occurred => use result.ErrorMessage to get more details
}
else
{
// everything went fine => use the result.SomeResult here
}
Of course the results can be any other complex object instead of (as shown in this example) a string.