Bill Blogs in C#

Bill Wagner discusses C#, LINQ, and other items of interest

Duck Typing in C# 4.0

I’ve been having fun learning the new upcoming C# 4.0 features Anders described at PDC (see video here). One of the the more interesting areas is dynamic, and the ways you can use dynamic to support duck typing.

In C# 4.0, you can create methods that take parameters that are dynamic. That means those parameters are statically typed to be dynamic.

For example, this method is a simple bit of code that writes information about an object to the console:

   1: public static void PrintLabel(dynamic thing)
   2: {
   3:     Console.WriteLine("ID: {0}, Label: {1}", thing.ID, thing.Label);
   4: }

You can call it with any type that supports an ID property (or field), and a Label property (or field).

For example, you can pass anonymous types to methods that expect dynamic types:

   1: var foo = new { ID = 1, Label = "This is a string" };
   2:  
   3: PrintLabel(foo);

You can even use different anonymous types, with different static types for the ID and Label properties:

   1: var foo2 = new { ID = "1234", Label = "This is a string" };
   2:  
   3: PrintLabel(foo2);

You can even pass a type that has a user defined type for the ID or Label property.

Suppose you created this sample class:

 

   1: class Sample
   2: {
   3:     public string Name
   4:     {
   5:         get;
   6:         set;
   7:     }
   8:  
   9:     public override string ToString()
  10:     {
  11:         return "My Name is " + Name;
  12:     }
  13: }

You can create a type (anonymous type below) that uses a Sample object as the label:

   1: var foo3 = new { ID = "1234", Label = new Sample() { Name = "Bill Wagner" } };
   2:  
   3: PrintLabel(foo3);

This is a powerful new way to create algorithms that get resolved at runtime. However, it will require a bit of practice, and more testing to understand when to leverage this feature. There are performance costs for runtime dispatch. The team is doing everything they can to improve the performance, but runtime dispatch is different than static dispatch.

On the other hand, the dynamic dispatch is a powerful feature. I will continue to look for opportunities where this feature will be the right solution.

Published Tue, Nov 11 2008 10:22 PM by wwagner

Comments

# re: Duck Typing in C# 4.0@ Wednesday, November 12, 2008 10:32 AM

Great post. Short, simple, and informative. Thanks

by Phil