Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting Exceptions in C#

Why do I get an InvalidCastException when trying to do this?

throw (ArgumentNullException)(new Exception("errormessage", null));

This is a simplified version of the following function.

public static void Require<T>(bool assertion, string message, Exception innerException) where T: Exception
    {
        if (!assertion)
        {
            throw (T)(new Exception(message, innerException));
        }
    }

The complete error message is:

System.InvalidCastException : Unable to cast object of type 'System.Exception' to type 'System.ArgumentNullException'.

like image 440
davehauser Avatar asked Sep 04 '25 16:09

davehauser


2 Answers

I have the impression that you are instantiating a base class and trying to cast it as a derived class. I don't think you are able to do this, as Exception is more "generic" than ArgumentNullException. You could do it the other way around though.

like image 52
Wagner Silveira Avatar answered Sep 07 '25 16:09

Wagner Silveira


You may want to try this instead:

public static void Require<T>(bool assertion, string message,
    Exception innerException) where T: Exception
{
    if (!assertion)
    {
        throw (Exception) System.Activator.CreateInstance(
            typeof(T), message, innerException);
    }
}
like image 27
TrueWill Avatar answered Sep 07 '25 17:09

TrueWill