Find the inner-most exception without using a while loop?

Looping through InnerExceptions is the only reliable way.

If the caught exception is an AggregateException, then GetBaseException() returns only the innermost AggregateException.

http://msdn.microsoft.com/en-us/library/system.aggregateexception.getbaseexception.aspx


Oneliner :)

while (e.InnerException != null) e = e.InnerException;

Obviously, you can't make it any simpler.

As said in this answer by Glenn McElhoe, it's the only reliable way.


I believe Exception.GetBaseException() does the same thing as these solutions.

Caveat: From various comments we've figured out it doesn't always literally do the same thing, and in some cases the recursive/iterating solution will get you further. It is usually the innermost exception, which is disappointingly inconsistent, thanks to certain types of Exceptions that override the default. However if you catch specific types of exceptions and make reasonably sure they're not oddballs (like AggregateException) then I would expect it gets the legitimate innermost/earliest exception.


If you don't know how deep the inner exceptions are nested, there is no way around a loop or recursion.

Of course, you can define an extension method that abstracts this away:

public static class ExceptionExtensions
{
    public static Exception GetInnermostException(this Exception e)
    {
        if (e == null)
        {
            throw new ArgumentNullException("e");
        }

        while (e.InnerException != null)
        {
            e = e.InnerException;
        }

        return e;
    }
}