views:

153

answers:

3

In the C# 4.0 demos, I'm seeing lots of code that uses the dynamic type. For example, the following code sets the value of an Excel cell:

excel.Cells[1, 1].Value = ...

However, you can also access the cell in an early bound manner with a cast:

((Range)excel.Cells[1, 1]).Value = ...;

Why don't the Excel COM library just describe the Cell type as a Range type in the first place? Similarly, all the arguments to the following method are dynamic:

excel.ActiveWorkbook.Charts.Add(...)

Why couldn't the arguments have been static? Looking at the Excel object model, there are dynamic types everywhere. Is this due to limitations in the expressiveness in COM? Is there a pattern to when dynamic types rather than static types are used in COM libraries?

+1  A: 

The COM library exposes this as a variant, which could mean any number of things. It's really the Office library's "fault" for doing so many things with variants.

The dynamic type is the nearest .NET equivalent to variant (now it exists) but the team didn't want to change tlbimp to generate dynamic types in PIAs for backward compatibility reasons. You'll only get the "variant to dynamic" conversion in C# 4 when linking a PIA (building the bits you use into your own assembly) instead of referencing it.

Jon Skeet
+1  A: 

In the C# 4.0 demos, I'm seeing lots of code that uses the dynamic type.

Since dynamic is one of the biggest changes in C# 4.0, I'd be hugely surprised if this wasn't the case. That doesn't mean you should immediately start writing all your code with dynamic - simply that you should recognise when it might be useful.

The variance and optional/named argument changes are appreciated too, of course - but make a much shorter demo.

Historically, Office (in particular) has been such a pig to program against that this is a "big thing* for people who automate Office.

  • people who consume COM (and Office especially)
  • people who consume DLR types (IronPython etc)
  • people who talk to dynamic systems such as javascript (Silverlight etc)

Personally, I don't expect dynamic to revolutionise the way I program in C#, but it is big for some people:

Marc Gravell
+1  A: 

Actually this is because Office com library was created with Visual Basic in mind.

Even more you can think that entire object hierarchy was created for VB (plain VB without .net). And VB historically created such way that it is simple to use IDispatch'able com interfaces from it (using late binding).

And what we have now it's a burden of backward compatibility.

arbiter