I have the following code:
public static void Main() {
Exception exception = new Exception("1", new Exception("2"));
Exception inner = exception.InnerException;
inner = new Exception("3");
Console.WriteLine(exception);
Console.ReadLine();
}
This should print an exception with message "1"
and with an inner exception, that has the message "3"
However, when printed, the inner exception has the message "2"
.
How can this happen? Am I not modifying the reference object? Is a copy of the object returned to me when I call exception.InnerException
?
This should print an exception with message "1" and with an inner exception, that has the message "3"
No, it shouldn't - because you're not modifying the object that the exception
variable refers to at all. Instead, you're declaring a variable and giving it an initial value using exception
:
Exception inner = exception.InnerException;
This copies the value of exception.InnerException
(which is a reference) to the inner
variable. Then in the next line you're ignoring the current value and just giving inner
a different value:
inner = new Exception("3");
That doesn't change anything about exception
. The fact that the original value of inner
happened to be fetched from the exception.InnerException
property doesn't affect the assignment of the new value to inner
at all. You might as well just have written:
Exception inner = new Exception("3");
You can't change Exception.InnerException
after the exception has been constructed - the InnerException
property is read-only. Even if it were a writable property, your code wouldn't have done what you wanted. Instead, you'd have needed:
// This won't work because InnerException is read-only, but it would *otherwise*
// have worked.
excetion.InnerException = new Exception("3");
See more on this question at Stackoverflow