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# 5.0 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.