A Programmer's Guide to C# 5.0 by Eric Gunnerson & Nick Wienholt

A Programmer's Guide to C# 5.0 by Eric Gunnerson & Nick Wienholt

Author:Eric Gunnerson & Nick Wienholt [Gunnerson, Eric & Wienholt, Nick]
Language: eng
Format: epub, pdf
Tags: C#, Computers, Programming, Microsoft Programming, Programming Languages
ISBN: 9781430245933
Publisher: Apress
Published: 2012-11-07T05:00:00+00:00


CHAPTER 24

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 that the type of jane will be whatever the type of the expression is, which is also Employee in this example.

The dynamic keyword is very different, in that it does not equate to a specific type. It means “I don’t know what type this thing is, so just keep a reference to it. We’ll figure out what it can do later.” Since all of these variables are references to instances of the Employee class, you can write the following:

Console.WriteLine(george.Name);

Console.WriteLine(jane.Name);

Console.WriteLine(astro.Name);

When you write george.Name or jane.Name, it means something very simple. Since you know that the type is Employee, you know that there is property named Name, and you merely call the getter of the Name property of the instance.1

When you write astro.Name, it means something very different; since you declared astro to be dynamic, all you know is that it is an instance of some object, but you don’t know what that object can do when you compile the code.

To evaluate astro.Name, you need to do the following:

Determine whether astro has a member named Name.

Determine whether the usage of astro.Name is valid in this context.

Figure out that Name is a property and has a specific get method.

Call the property getter.

Determine how the return type of the property getter should be treated and whether any conversions are required.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.