Reputation:
While writing
var e = element.NextSibling as HtmlElement;
I get an invalid cast exception. I thought as prevents cast exception and returns null? because thats what i wanted/excepted. Either tell me how do i get e to be null instead of an exception? or why i got this exception when using the as keyword?
-edit- Correct it was element.NextSibling throwing the exception. How strange that its throwing a cast exception when i havent tried to cast it yet. I am not sure how to check if a next sibling exist. The error in NextSibling is below
Message "Unable to cast COM object of type 'System.__ComObject' to interface type 'IHTMLElement'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{3050F1FF-98B5-11CF-BB82-00AA00BDCE0B}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE))." string
Upvotes: 3
Views: 792
Reputation: 391326
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.
Upvotes: 13