That's like trying to do:
FileStream stream = (FileStream) new object();
What file would it read from or write to?
You can only cast a reference to a type if the actual object is that type or has that type in its hierarchy. So this will work:
Exception exception = new ArgumentException();
ArgumentException argumentException = (ArgumentException) exception;
and this will work too:
Exception exception = new ArgumentOutOfRangeException();
// An ArgumentOutOfRangeException *is* an ArgumentException
ArgumentException argumentException = (ArgumentException) exception;
but your example won't because an instance of just System.Exception
isn't an instance of System.ArgumentException
.
Note that this has nothing to do with exceptions, really - the same logic is applied for all reference types. (With value types there's also boxing/unboxing to consider. Oh, and there's also potentially user-defined conversions, e.g. from XElement
to string
- but we'll leave those out of it too for the moment.)