Click here to Skip to main content
14,982,875 members
Articles / Programming Languages / C#
Posted 21 Sep 2008

Tagged as


31 bookmarked

Late Binding Helper Library

Rate me:
Please Sign up or sign in to vote.
3.78/5 (5 votes)
21 Jan 2009BSD4 min read
Simple library which aims to simplify late binding calls with C#


This article describes a helper library for performing late binding calls to an instance of a type using the .NET framework. Additionaly as Automation calls (former OLE Automation) are encapsulated under the .NET Framework by the Late Binding system, this library also simplifies interprocess communication using Automation on applications which supports it, e.g: Microsoft Office suite. As the C# language is still far away from the model available for VB.NET, the intention is to provide a simpler model for that language, although the library can be consumed by any .NET language.

With C#4.0 the dynamic keyword will be added so -with time- this library will be deprecated. But C# 4.0 isn't out yet, and even when it comes out, there will be still a lot of projects using previous versions of the C# language which could benefit from this library.

Finally the interface for the library has completly changed. Now it's designed as a fluent interfece, which really improves both usability and code readability. [^]


Late Binding consists in performing the name binding for a method call or field access at runtime instead of at compile time. The later is called -predictably- early binding. An example of early binding could be many of the method calls we can see in C# every day:

System.IO.StreamReader sr = new System.IO.StreamReader(".//myFile.txt");

//early binding call
string fileContent= sr.ReadToEnd();

Early binding allows compile-time optimization and type-checks, among other things, but in order to do that, we must provide concrete references to the types used. In the example above, a reference to mscorlib.dll assembly, which contains the data for the type System.IO.StreamReader, must be provided to the C# compiler.

Note that in a strict definition of early binding, a virtual / abstract method is a late binding call, as the resolution of the real method called for a virtual method depends on the type of the object, which is evaluated at runtime. This is called Dynamic Binding [^], and it will not be treated as Late binding in this article.

Late Binding swaps the security and optimization of early binding for a more wild approach: we just take a generic object and command it to perform an operation with a concrete signature. If the object happens to expose an operation which exactly matches the signature then all will be ok and the CLR will perform the operation at runtime.

But, what if the object does not expose that operation? In that case, bad things will happen:


Using the Library

The source includes a Visual Studio 2005 solution (which can safely be converted to a 2008 one) containing three projects:

  • A project for the library itself
  • A project a simple type for testing
  • A project with Unit Test (NUnit based), which also serves as code sample

The external libraries needed to compile the code (NUnit) are also included: just download/checkout and build!

All late binding functionality is based on the interface LateBindingHelper.IOperationInvoker

Acquisition of an IOperationInvoker interface is done using a Factory: LateBindingHelper.BindingFactory which allows creation of an IOperationInvoker binded to an object instance. The factory provides various possibilities for instanciating an IOperationInvoker:

  • Using an instance of an object as a "prototype", so the IOperationInvoker instance is binded to that particular object instance
  • Using a System.Type to create a new instance of the Type at runtime (optionally arguments for the constructor can be also specified)
  • Using a pair of strings defining both the Assembly and the Type of the object we want to instanciate.
  • Using a string which defines an specific application ProcID
MyClass myClassInstance = new MyClass();

//Late Binding calls will be dispatched to the myClassInstance object
IOperationInvoker lbf1 = BindingFactory.CreateObjectBinding( myClassInstance );

//Creates a new MyClass object instance where the late binding call will be dispatched 
//using the default constructor
IOperationInvoker lbf2 = BindingFactory.CreateObjectBinding( typeof(MyClass) );

int integerArgument = 2008;
//Creates a new MyClass object instance where the late binding call will be
//dispatched passing arguments to the constructor
IOperationInvoker lbf3 = BindingFactory.CreateObjectBinding( typeof(MyClass),
    integerArgument );

BindingFactory.CreateAutomationBinding() factory makes a binding to an Automation application given its Running Object Table (ROT) name or ProcID:

IOperationInvoker word = BindingFactory.CreateAutomationBinding("word.application");

Once we have an instance of an IOperationInvoker interface, we can send any operation we want to the object using the interface, and the operation will be issued at runtime

Here are some code examples showing the different operations we can perform:

Calling a Method

//Method call without parameters and no return value
myLBInvoker.Method ("Method1" ).Invoke();

//Method call with parameters and no return value (or we don't need the return value)
int arg1 = 1;
double arg2 = 2.3;
myLBInvoker.Method( "Method2" )

//Method call without parameters and a return value of type int
int result;
result = myLBInvoker.Method( "Method3" )

//Or with explicit casting			
result = (int)myLBInvoker.Method( "Method3" )

//Method call with parameters and a return value of type int
int result;
int arg1 = 1;
double arg2 = 2.3;
result = myLBInvoker.Method( "Method2" )

//Or with explicit casting			
result = (int)myLBInvoker.Method( "Method2" )

Calling a Method with Reference Parameters

int refValue = 10;
double notRefParam1 = 20;
bool notRefParam2 = true;

//Make the call. Args.ByRefIndexs indicates the index number of the arguments
//which are passed as reference

//Recover the new value for the parameter passed by reference
refValue = (int)myLBInvoker.LastCallParameters[2];

Accessing Properties or Fields

//Get property value
bool boolResult;
boolResult = myLBInvoker.Property(("Property1").Get<bool>();

//With explicit cast
boolResult = (bool)myLBInvoker.Property("Property1").Get<object>();

//Get field value
int intResult;
intResult = myLBInvoker.Field("field1").Get<int>();
//With explicit cast
intResult = (int)myLBInvoker.Field("field1").Get<object>();

//Set property value

//Set field value


//Get object at index position
string result;
result = myLBInvoker.Index(5).Get<string>();
//Set value for an index position
//Works with any object as indexer:
result = myLBInvoker.Index("myStringIndexer").Get<string>();

One More Thing: IOperationInvoker as Return Type

You can use IOperationInvoker as a return type for an operation, and if you do so, you'll receive an working instance of an object defining the IOperationInvoker interface. That means that you can concatenate late binding call on different objects:

IOperationInvoker yetAnotherOrdersManager = BindingFactory.CreateBinding(

int firstOrderID = yetAnotherOrdersManager 
          //Here we return a list of orders
             //We access the first order... hoping we have at least one order
             //stored so no nasty exception is throw.
                //Access orderID field and save it.        

Word Automation Example

A test -disabled by default- is included as an example to create a binding to Microsoft Word and control the application with the library using Automation. The code is also listed here:

IOperationInvoker wordApp = BindingFactory.CreateAutomationBinding("Word.Application");

//Get Word objects to interop operations
IOperationInvoker document = wordApp.Property("Documents").Get<IOperationInvoker>();

IOperationInvoker selection = wordApp.Property("Selection").Get<IOperationInvoker>();

string str = "Hello World!";

//Make workd visible

//Activate bold

//Change font size

foreach (char c in str)

//Hide Word
bool visibility = wordApp.Property("Visible").Get<bool>();
visibility = !visibility;

//We need to get the type of the enumeration, that breaks the Late Binding
//approach as we need a way to know a specific type, and it's aseembly
//Type enumType = Assembly
//      .LoadWithPartialName("Microsoft.Office.Interop.Word")
//      .GetType("Microsoft.Office.Interop.Word.WdSaveOptions", false);
//word.Call("Quit", Activator.CreateInstance(enumType)));

//But if we know the equivalent int to the enum value it will work
//WdSaveOptions.wdDoNotSaveChanges == 0


Related Articles & Bibliography


  • January 2009 -- Updated article to reflect changes in the interface
  • September 2008 -- Initial version



This article, along with any associated source code and files, is licensed under The BSD License


About the Author

Ricardo Amores Hernández
Software Developer (Junior)
Spain Spain
No Biography provided

Comments and Discussions

GeneralThe Helper Library and the Word.Documents Collection Pin
bbeard335-Nov-10 8:37
Memberbbeard335-Nov-10 8:37 
GeneralRe: The Helper Library and the Word.Documents Collection Pin
Ricardo Amores Hernández5-Nov-10 10:29
MemberRicardo Amores Hernández5-Nov-10 10:29 
GeneralRe: The Helper Library and the Word.Documents Collection Pin
bbeard338-Nov-10 10:14
Memberbbeard338-Nov-10 10:14 
GeneralVery Usefull Pin
waterloomatt28-Jul-09 5:38
Memberwaterloomatt28-Jul-09 5:38 
GeneralI Don't get it Pin
tonyt21-Jan-09 22:32
Membertonyt21-Jan-09 22:32 
GeneralRe: I Don't get it Pin
Ricardo Amores Hernández21-Jan-09 23:08
MemberRicardo Amores Hernández21-Jan-09 23:08 
GeneralQuestion Pin
Mario_F27-Sep-08 13:05
MemberMario_F27-Sep-08 13:05 
GeneralRe: Question Pin
Ricardo Amores Hernández28-Sep-08 9:26
MemberRicardo Amores Hernández28-Sep-08 9:26 
GeneralRe: Question Pin
Mario_F28-Sep-08 10:08
MemberMario_F28-Sep-08 10:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.