AS. the answer was extended few times, as more and more info was uncovered turning the question from "what is CType function?" to "How to convert OleVariant to a required Interface type?". Thus the answer gradually covers all those topics.
So, you met unknown function in Microsoft Visual Basic code. What is one to do, when he meets something yet unknown? Go Google.
Google.com with text CType MSDN gives us this link in its top results: http://msdn.microsoft.com/en-us/library/vstudio/4x2877xb.aspx
Returns the result of explicitly converting an expression to
a specified data type, object, structure, class, or interface.
If no conversion is defined from expression to typename (for example,
from Integer to Date), Visual Basic displays a compile-time error message.
So we have to reproduce typecast in Delphi, preferably compile-type type-cast, if possible.
Google.com with text typecast docwiki gives us this link in its top results:
Which in turn gives us one more link referenced in the text:
So you have two syntaxes to try. One you tried and ruled out - the one with AS operator. Then try another, direct typecast syntax.
stylesheet := IHTMLStyleSheet( document.styleSheets.item(0) );
Sometimes if above fails it also helps doing double typecast, Variant -> IUnknown -> certain interface, but in many cases that is but redundant version of the upper code.
stylesheet := IHTMLStyleSheet( IInterface( document.styleSheets.item(0) ) );
Well, now that it was told that the source expression datatype is OleVariant we can read documentation with more precise aim, about Variant datatype conversions (OleVariant is little different from Variant in modern Delphi):
- AS operator is applicable to classes, objects and interfaces. It is not applicable to
Variant expressions. This answers the original "why we cannot..." question.
- Documentation on
Variant type suggests converting it using direct typecast syntax.
.
stylesheet := IInterface( document.styleSheets.item(0) ) as IHTMLStyleSheet;
If wished, you can even use (over?)defensive programming using http://docwiki.embarcadero.com/Libraries/XE2/en/System.Variants.VarType to check that you got varUnknown or varDispatch before attempting at getting IUnknown out of the returned value.
PS. The question seems as a duplicate now.