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'.
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With