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: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access