Why .NET exceptions are mutable?
-
28-09-2019 - |
Pergunta
I'm wondering why .NET exceptions classes from Base Class Library has some mutable members by default
- Why I can change the
Source
,HelpLink
and values fromData
, but can't change anything else like theMessage
? - Why throwing the exception rewrites the
StackTrace
making it mutable too? Is appending the stack trace information to existing trace would be better design (but still mutable)? - What possible improvements in .NET exceptions design may be?
I'm interesting just in design choices...
Solução
The StackTrace
makes sense to me, at least. The idea is that an Exception
(as an object) may be passed around, returned from methods, etc. The StackTrace
is only important as an exception is thrown and caught. In a sense, StackTrace
is really more of a property of the throwing of the exception, not the Exception
object itself.
Regarding the mutability of the other properties, I assume it is just because it's easier to construct an instance by assigning to properties rather than forcing them all into the constructor. Remember that at the time Exception
was designed, C# did not have optional parameters.
You could consider a re-design where Exception
and derived classes are immutable, but this would require an exception factory or builder class. It would just make deriving from Exception
that much more complex.