I have the following code that generates a compiler error:
Boolean IConvertible.ToBoolean(IFormatProvider provider)
{
ThrowHelper.ThrowInvalidCast(typeof(MyType), typeof(Boolean));
}
The compiler is complaining that not all code paths return a value. The problem here is that ThrowHelper will ALWAYS throw an error. It is a static class calling a static method.
I understand that I can satisfy the compiler with a silly "return true" after the ThrowHelper
call, but that seems like unnecessary code. I know I can suppress warning messages, but when I tried to use the SuppressMessageAttribute
it doesn't stop the compiler from complaining. Any way to suppress this error only for this method?
There is no way to suppress an error other than to fix it.
An error, by its nature, is indicating that the compiler believes it cannot generate valid code. The only way to suppress errors is to fix them. Just add the
return
statement it wants and then raise an issue on Microsoft Connect indicating that you believe the compiler is getting this one wrong.I suspect, however, that this is expected behaviour as the compiler is not aware that the method you are calling will always throw and to determine that in a predictable manner for any possible call tree would be difficult, if not impossible (imagine if you called a chain of 20 methods before concluding with a throw).