Casting Exceptions in C#
17,146
Solution 1
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.
Solution 2
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);
}
}
Solution 3
System.Exception is not the object you're casting to; it's that simple. Throw an exception of the different type directly if you want to raise that type.
Author by
davehauser
Updated on June 04, 2022Comments
-
davehauser almost 2 years
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'.
-
zneak over 13 yearsExactly. You can create a
NullReferenceException
and then cast it into anException
, but you can't create anException
and then cast it into aNullReferenceException
. -
Steven Sudit over 13 yearsThat's correct.
Exception
is the base,ArgumentNullException
is the child. -
davehauser over 13 yearsThat gives me a "System.Reflection.AmbiguousMatchException : Ambiguous match found."
-
TrueWill over 13 yearsWorks for me under .NET 4.0; tested in LINQPad 4 with a custom Exception descendant passed for T. Just tried it again with the following and it worked: Require<ArgumentNullException>(false, "test", new InvalidOperationException());