ArgumentException argumentException = (ArgumentException)new Exception();
throws:
System.InvalidCastException: Unable to cast object of type ‘System.Exception’ to type ‘System.ArgumentException’.
Why can I not cast an Exception (less definition, I would think) to an ArgumentException (more definition, I would think)?
That’s like trying to do:
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:
and this will work too:
but your example won’t because an instance of just
System.Exceptionisn’t an instance ofSystem.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
XElementtostring– but we’ll leave those out of it too for the moment.)