Visual Studio 2010!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.
ADVERTISEMENT
ADVERTISEMENT

 

DevSource.com: Your Source for Visual Studio on Facebook
ADVERTISEMENT
Using COM and C# 4.0
By DevSource

Rate This Article: Add This Article To:

MSDN, a well known source for all things .Net Developer, walks through some of the new uses of dynamic keywords and COM objects, showing how flexible the new .Net 4 Dynamic Keyword typing can be.

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.




Discuss Using COM and C# 4.0
 
>>> Be the FIRST to comment on this article!
 

 
 
>>> More Microsoft Languages Articles          >>> More By DevSource