How to set the InnerException of custom Exception class from its constructor

How can I set the InnerException property of an Exception object, while I'm in the constructor of that object? This boils down to finding and setting the backing field of a property that has no setter.

BTW: I have seen this evain.net - Getting the field backing a property using Reflection but looking for non IL-based solution, if possible.

The constructor of Exception is the place where the Exception type is created, so I cannot call it using the base class constructor MyException() :base(...) etc.


You set the inner exception by calling the base ctor:

public MyException(string message, Exception innerException)
       : base(message, innerException) {...}

If you need to run some code to get the exception, use a static method:

public MyException(SomeData data) : base(GetMessage(data), GetInner(data)) {...}
static Exception GetInner(SomeData data) {...} // <===== your type creation here!
static string GetMessage(SomeData data) {...}

The Exception class has an overloaded constructor accepting the inner exception as a parameter:

Exception exc = new Exception("message", new Exception("inner message"));

Is this what you are looking for?


Why can't you just call the constructor taking the InnerException as a parameter? If for some reason it's not possible, the backing field in System.Exception is:

private Exception _innerException;

I found it out using Redgate's Reflector. Using reflection I suppose you could set the inner exception.

Edit: In most cases it's not a good idea to access private fields via reflection, but I don't know enough about NT's case to know for sure if it's a good or bad idea.