Sunday 1 February 2009

C#4, Dynamic Types and Sage

I was reading an article in this month's VSJ, and I was interested to read about C# 4.0's new Dynamic type. This type is C#'s answer to the weakly typed objects of languages like Basic, PHP, etc., This gives some advantages when dealing with .NET interfaces that lay above COM infrastructures, especially the Sage Data Objects library.

Therefore, with dynamics, code such as

SageDataObject50.InvoicePost InvPost;

InvPost = (SageDataObject50.InvoicePost)ws50.CreateObject("InvoicePost");

can become:

dynamic dInvoicePost = ws50.CreateObject("InvoicePost");

The cast to InvoicePost will be done at runtime, and the code will still compile, even if you don't know what the return object of this particular CreateObject method can be cast to.

The downside to this, as in every weakly typed language, is that many errors will not be spotted until runtime, and you may need to go through a process of trial-and-error to see what methods are available on a particular dynamic type.

According to VSJ this method for invoking COM objects should actually be more efficient, and certainly more elegant than using reflection.

Hopefully, I should be able to find a CTP download of C#4 to put together a code example.