Binding in C#

Early binding

With early binding, Visual C# uses type information that is available about the Office Application in question to bind directly to the methods or properties it needs to use. The compiler can perform type and syntax checks to ensure that the correct number and type of parameters are passed to the method or property, and that the returned value will be of the expected type. Because less work is required at run time to make a call to a property or method, early binding is sometimes faster; however, although early binding may be faster, performance differences when compared to late binding are often negligible.

Early binding does have the minor disadvantage that it can introduce possible version compatibility issues. For example, suppose that an Automation server such as Microsoft Excel 2002 introduces a new method or property that was unavailable in Excel 2000, or makes a change to an existing property or method. These changes may alter the binary layout of the object and cause problems with a Visual C# application that uses the Excel 2002 type information to automate Excel 2000. To avoid this problem with early binding, it is generally recommended that you use the type information for the earliest version of the Office Application that you wish to support when you develop and test your Automation client.

The following steps demonstrate how to build an Automation client that uses early binding. Note that, as the steps illustrate, early binding requires you to reference the type library for the Automation client.

 

Late binding

In contrast to early binding, late binding waits until run time to bind property and method calls to their objects. To do this, the target object must implement a special COM interface: IDispatch. The IDispatch::GetIDsOfNames method allows Visual C# to interrogate an object about what methods and properties it supports and the IDispatch::Invoke method then allows Visual C# to call those methods and properties. Late binding in this fashion has the advantage of removing some of the version dependencies that are inherent with early binding. However, it has the disadvantages of removing compile-time checks on the integrity of automation code, as well as not providing Intellisense features that can provide clues to correct calls to methods and properties.

To use late binding in Visual C#, use the System.Type.InvokeMember method. This method calls IDispatch::GetIDsOfNames and IDispatch::Invoke to bind to the Automation server's methods and properties.