Recording error messages from an exception How do I shorten these if else statements? As you can see, those elses are repeated.

if (exception.InnerException != null)
{
    if (!string.IsNullOrEmpty(exception.InnerException.Message))
    {
        errorMessage = exception.InnerException.Message;
    }
    else if (!string.IsNullOrEmpty(exception.Message))
    {
        errorMessage = exception.Message;
    }
    else
    {
        errorMessage = exception.ToString();
    }
}
else if (!string.IsNullOrEmpty(exception.Message))
{
    errorMessage = exception.Message;
}
else
{
    errorMessage = exception.ToString();
}
In C# 6 or later you can write it in a single line of code using the null conditional operator (?.) and the null coalescing operator (??):

ver errorMessage =  exception.InnerException?.Message ?? 
                    exception.Message ?? 
                    exception.ToString();


Note that it will not handle empty strings (if the Message property contains an empty string it will be returned), but then again, I've never heard of exceptions with empty strings as their message...

If you fear that situation, you can always create an extension method for strings that will return null for empty strings:

public static string NullIfEmpty(this string str)
{
    return string.IsNullOrEmpty(str) ? null : str;
}


and then use it like this:

ver errorMessage =  exception.InnerException?.Message?.NullIfEmpty() ?? 
                    exception.Message?.NullIfEmpty() ?? 
                    exception.ToString();