2010-07-29
| Rate This Article: | Add This Article To: |
To read this article in its entirety, please visit MSDN: C# 4.0, the Dynamic Keyword and COM
Easy Access COM Objects
An object is said to be dynamic when its structure and behavior aren’t fully described by a statically defined type that the compiler knows thoroughly. Admittedly, the word dynamic sounds a bit generic in this context, so let’s look at a simple example. In a scripting language such as VBScript, the following code runs successfully:
Set word = CreateObject("Word.Application") The CreateObject function assumes that the string it gets as an argument is the progID of a registered COM object. It creates an instance of the component and returns its IDispatch automation interface. The details of the IDispatch interface are never visible at the level of the scripting language. What matters is that you can write code such as:
Set word = CreateObject("Word.Application")
word.Visible = True
Set doc = word.Documents.Add()
Set selection = word.Selection
selection.TypeText "Hello, world"
selection.TypeParagraph()
doc.SaveAs(fileName) In this code, you first create a reference to a component that automates the behavior of the underlying Microsoft Office Word application. Next, you make the Word main window visible, add a new document, write some text into it and then save the document somewhere. The code is clear, reads well and, more importantly, works just fine.
The reason this works, however, is due to a particular capability offered by VBScript—late binding. Late binding means that the type of a given object isn’t known until the execution flow hits the object. When this happens, the runtime environment first ensures that the member invoked on the object really exists and then invokes it. No preliminary check whatsoever is made before the code is actually executed.
|
![]() |
|


