-2

iam to Unable to cast object of type 'HtmlAgilityPack.HtmlDocument' to type 'mshtml.IHTMLDocument2'

HTMLDocument doc = new HTMLDocument();
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;    
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
chandu
  • 25
  • 7
  • Seems like error is pretty self-descriptive. You cannot cast type A to type B, like you cannot cast boolean to date – Sergey Berezovskiy Jul 06 '17 at 13:12
  • in this way we can cast the system.windowsforms.document to html IHTMLDocument2 IHTMLDocument2 doc = (IHTMLDocument2)webBrowserDomDocument.Document.DomDocument; it is possible but i was to cast in HTML AgilityP ack also – chandu Jul 06 '17 at 13:20

2 Answers2

0

In order to cast type A to type B, one of following should be true

  • Type A should be inherited from type B, or it should implement type B if it's an interface. Implicit conversion will work in this case
  • Type B should be inherited from type A and variable which you are casting should hold an instance of type B.
  • There should be explicit operator defined in either type which performs conversion

If none is true, then you'll get a runtime exception. For types HtmlAgilityPack.HtmlDocument and mshtml.IHTMLDocument2 both conditions are not satisfied.

UPDATE: Seems like you have a typo - instead of declaring doc variable as HTMLDocument you have declared it as HtmlDocument. C# is a case-sensitive language.

Further reading: Casting and Type Conversions (C# Programming Guide)

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
-1

It is because HTMLDocument does not implement IHTMLDocument2 so there's no known path to perform the cast.

Kees
  • 1,408
  • 1
  • 15
  • 27
  • implementation is not necessary – chandu Jul 06 '17 at 13:24
  • In this case it is because there's no explicit operator defined to perform the conversion. If you cast from object1 to object2 there must be some sort of relation between those types like inheritance, implementation or an operator that tells how the conversion should work. – Kees Jul 06 '17 at 13:27