O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

dynamic in Noninterop Scenarios?

The main motivation behind dynamic’s introduction was to make it possible to use Office without writing horrible code. It also has uses in other interop scenarios such as dealing with browser script in Silverlight, and working with dynamic languages. But would you ever use it in a pure C# scenario? The dynamic style has become increasingly fashionable in recent years—some popular JavaScript libraries designed for client-side web code make cunning use of dynamic idioms, as do certain web frameworks. Some developers even go as far as to claim that a dynamic style is inherently superior to a static style. If that’s the way the wind is blowing, should C# developers follow this trend?

Tantalizingly, for those keen on dynamic languages, dynamic has brought some dynamic language features to C#. However, the key word here is some. C# 4.0 added dynamic to improve certain interop scenarios, not to support whole new programming idioms. It is therefore not helpful to think of dynamic in terms of “dynamic extensions for C#.”

If you attempt to use C# as though it were a fully fledged dynamic language, you’ll be stepping outside the language’s core strength, so you will inevitably run into problems. We’ve already seen a LINQ example that did not mix well with dynamic, and that failure was a symptom of a broader problem. The underlying issue is that delegates are not as flexible as you might expect when it comes to dynamic behavior. Consider the method shown in

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required