I want to test the following code:
private bool TestException(Exception ex)
{
if ((Marshal.GetHRForException(ex) & 0xFFFF) == 0x4005)
{
return true;
}
return false;
}
I’d like to set up the Exception object somehow to return the correct HResult, but I can’t see a field in the Exception class which allows this.
How would I do this?
I found three ways to do this:
Use the
System.Runtime.InteropServices.ExternalExceptionclass, passing in the error code as a parameter:Thanks to @HansPassant for his comment explaining this.
Pass a mock exception using inheritance to access a protected field:
Use .NET Reflection to set the underlying field:
Passing any one of these exceptions to the method in the question, will result in that method returning
true. I suspect the first method is most useful.