I encountered a bizarre bug (?) while refactoring some code.
For some unknown reason, I get a compiler error when passing a dynamic variable to a static method in a throw statement.
dynamic result = comObj.getfoo(bar);
// ....
throw ApiException.FromResult(result);
Error CS0155
The type caught or thrown must be derived from System.Exception
This makes no sense as the returned value is derived from System.Exception.
Furthermore, what makes me lean toward this being a bug, is that error can be circumvented by either:
- changing
dynamic
tovar
var result = 0;
- by casting the variable to
object
.
throw ApiException.FromResult((object)result);
Any ideas?
/* PS: code omitted for brevity */
using System;
public class Program
{
public class ApiException : Exception
{
public static ApiException FromResult(object result)
{
return new ApiException();
}
}
[STAThread]
public static void Main(string[] args)
{
dynamic result = 0;
throw ApiException.FromResult(result);
}
}