CHAPTER 24

image

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 O’Reilly online learning.

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