Dynamic Typing

The vast majority of code written with C# is strongly typed. But there are scenarios where a strongly typed system doesn’t work, such as when dealing with some COM objects or working with dynamically typed languages. This chapter explores the support that C# provides for dynamically typed programming.

The dynamic Keyword

Dynamic provides a new way to declare variables. Consider the following code:

Employee george = new Employee("George", 15, 10M);var jane = new Employee("Jane", 13, 9M);dynamic astro = new Employee("Rastro", 7, 1M);

The first line declares that George is of type Employee. The second line uses var to declare ...

Get A Programmer's Guide to C# 5.0, 4th Edition now with the O’Reilly learning platform.

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