At the recent Microsoft Professional Developer's Conference there was a presentation by Anders Hejlsberg about The Future of C# which unveiled some of the upcoming features of C# 4.0. Of all the features announced, the one I found most interesting was the introduction of duck typing via a new static type called dynamic .

For those who aren't familiar with Duck Typing, here is the definition from Wikipedia

In computer programming, duck typing is a style of dynamic typing in which an object's current set of methods and properties determines the valid semantics, rather than its inheritance from a particular class. The name of the concept refers to the duck test, attributed to James Whitcomb Riley (see History below), which may be phrased as follows: If it walks like a duck and quacks like a duck, I would call it a duck. In duck typing one is concerned with just those aspects of an object that are used, rather than with the type of the object itself. For example, in a non-duck-typed language, one can create a function that takes an object of type Duck and calls that object's walk and quack methods. In a duck-typed language, the equivalent function would take an object of any type and call that object's walk and quack methods. If the object does not have the methods that are called then the function signals a run-time error.

This is perfectly illustrated with the following IronPython program

def PrintAt ( container , index ) : print "The value at [%s] is %s" % ( index , container [ index ] ) if __name__ == "__main__" : #create dictionary table = { 1 : "one" , 2 : "two" , 3 : "three" } #create sequence list = ( "apple" , "banana" , "cantalope" ) PrintAt ( table , 1 ) PrintAt ( list , 1 )

In the above program the PrintAt() simply requires that the container object passed in supports the index operator '[]' and can accept whatever type is passed in as the index. This means I can pass both a sequence (i.e. a list) or a dictionary (i.e. a hash table) to the function and it returns results even though the semantics of using the index operator is very different for lists and dictionaries.

Proponents of static typing have long argued that features like duck typing lead to hard-to-find bugs which are only detected at runtime after the application has failed instead of during development via compiler errors. However there are many situations even in statically typed programming where the flexibility of duck typing would be beneficial. A common example is invoking JSON or SOAP web services and mapping these structures to objects.

Recently, I had to write some code at work which spoke to a JSON-based Web service and struggled with how to deal with the fact that C# requires me to define the class of an object up front before I can use it in my application. Given the flexible and schema-less nature of JSON, this was a problem. I ended up using the JsonReaderWriterFactory to create an XmlDictionaryReader which maps JSON into an XML document which can then be processed flexibly using XML technologies. Here's what the code looked like

using System; using System.IO; using System.Runtime.Serialization.Json; using System.Text; using System.Xml; namespace Test { class Program { static void Main( string [] args) { string json = @"{ ""firstName"": ""John"", ""lastName"": ""Smith"", ""age"": 21 }" ; var stream = new MemoryStream ( ASCIIEncoding .Default.GetBytes(json)); var reader = JsonReaderWriterFactory .CreateJsonReader(stream, XmlDictionaryReaderQuotas .Max); var doc = new XmlDocument (); doc.Load(reader); //error handling omitted for brevity string firstName = doc.SelectSingleNode( "/root/firstName" ).InnerText; int age = Int32 .Parse(doc.SelectSingleNode( "/root/age" ).InnerText); Console .WriteLine( "{0} will be {1} next year" , firstName, age + 1); Console .ReadLine(); } } }

It works but the code is definitely not as straightforward as interacting with JSON from Javascript. This is where the dynamic type from C# 4.0 would be very useful. With this type, I could rewrite the above code as follows

using System; using System.IO; using System.Runtime.Serialization.Json; using System.Text; using System.Xml; namespace Test { class Program { static void Main( string [] args) { string json = @"{ ""firstName"": ""John"", ""lastName"": ""Smith"", ""age"": 21 }" ; var stream = new MemoryStream ( ASCIIEncoding .Default.GetBytes(json)); dynamic person = JsonObjectReaderFactory .CreateJsonObjectReader(stream, XmlDictionaryReaderQuotas .Max); Console .WriteLine( "{0} will be {1} next year" , person.firstName, person.age + 1); Console .ReadLine(); } } }

In the C# 4.0 version I can declare a person object whose class/type I don't have to define at compile time. Instead the property accesses are converted to dynamic calls to the named properties using reflection by the compiler. So at runtime when my [imaginary] JsonObjectReader dynamically creates the person objects from the input JSON, my application works as expected with a lot less lines of code.

It's amazing how Python-like C# gets each passing year.

FURTHER READING: