concept dynamic in category .net

appears as: dynamic
C# in Depth

This is an excerpt from Manning's book C# in Depth.

  • In C# 3, the assignment to worksheet would fail without a cast, because the type of the ActiveSheet property is represented as object. When using the embedded PIA feature, the type of ActiveSheet becomes dynamic, which leads to an entirely different feature.
  • C# has always been a statically typed language, with no exceptions. There have been a few areas where the compiler has looked for particular names rather than interfaces, such as finding appropriate Add methods for collection initializers, but there’s been nothing truly dynamic in the language beyond normal polymorphism. That changes with C# 4—at least partially. The simplest way of explaining it is that there’s a new static type called dynamic, which you can try to do almost anything with at compile time and let the framework sort it out at execution time. Of course, there’s more to it than that, but that’s the executive summary.

    Given that C# is still a statically typed language everywhere that you’re not using dynamic, I don’t expect fans of dynamic programming to suddenly become C# advocates. That’s not why the feature was introduced: it’s aimed primarily at interoperability. When dynamic languages such as IronRuby and IronPython joined the .NET ecosystem, it would have been crazy not to be able to call into C# code from IronPython and vice versa. Likewise, developing against COM APIs used to be awkward in C#, with an abundance of casts cluttering the code. Dynamic typing addresses all of these concerns. On the other hand, there are plenty of projects that use dynamic typing within C# to make data access boundaries simpler.

    Do you remember how many new bits of syntax were involved when you learned about LINQ? Well, dynamic typing is just the opposite: there’s a single contextual keyword, dynamic, which you can use in most places where you’d use a type name. That’s all the new syntax that’s required, and the main rules about dynamic are easily expressed, if you don’t mind a bit of hand-waving to start with:

  • An implicit conversion exists from almost any CLR type to dynamic.
  • An implicit conversion exists from any expression of type dynamic to almost any CLR type.
  • Expressions that use a value of type dynamic are usually evaluated dynamically.
  • The static type of a dynamically evaluated expression is usually deemed to be dynamic.
  • Listing 14.1. Using dynamic to iterate through a list, concatenating strings
    dynamic items = new List<string> { "First", "Second", "Third" }; dynamic valueToAdd = "!"; foreach (dynamic item in items) { string result = item + valueToAdd; Console.WriteLine(result); }