The dynamic Type

Now that we’ve identified key terminology related to dynamic operations, let’s take a step back and look at the “language surface” for the feature in C# 4.0. In essence, there’s just the dynamic keyword, which indicates that discovery of operations need to be deferred until runtime, relying on the (dynamic) runtime type rather than the (static) compile-time type. For example, in the following piece of code, s is statically typed to be a string:

string s = "Hello world";Console.WriteLine(s.ToUpper());

The compiler does make sure it’s impossible to assign anything other than a string (or in more general cases, anything that’s not compatible with the variable’s type) to s. Notice that the use of casts may result in runtime exceptions: ...

Get C# 4.0 Unleashed now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.