Are you sure it's this particular statement that is causing the exception to be thrown?
If you've wrapped it in a try/catch block to determine that it is, try picking it apart:
var next = element.NextSibling;
var e = next as HtmlElement;
Perhaps the exception is thrown from within .NextSibling?
In any case, it is not possible to override the as
operator in C#, so it should always do what you expect it to do, and not throw that exception. I suspect the problem is elsewhere, but looks like it comes from this location.
Edit: As suggested by @Jon Skeet in his deleted answer, I would also suggest you try to replicate the problem in a short, but complete, program, and post the program here in your question so that we can try to reproduce the problem ourselves. Also, trying to reproduce the problem in a shorter piece of code might give you valuable insight into the specific scenario you're experiencing in your main project.
Judging by the code, it looks like you're parsing HTML code. If element
is a HtmlElement object, then the .NextSibling
method itself does not contain a cast that would produce that problem, but it does call another .NextSibling
method through an interface reference, which means that Reflector alone won't tell me which object is involved here.
Edit in response to updated question: Unfortunately, I cannot help you with that part of the problem.
It appears that the call to .NextSibling
internally retrieves a COM object, which it believes should implement the IHTMLElement interface, but in fact it does not. This internal code, however, is using a hard cast, which thus fails with that exception.
I don't think you have any other choice than to wrap at the very least the call to .NextSibling
in a try/catch block to avoid this, unless you can find some patently wrong with the HTML code it is attempting to parse that you could correct instead.
Best of luck.