« But it has angle brackets! | Main | Fortunately, we can save ourselves by leaving the lights on while we’re not using them »

September 01, 2011

Dynamic interfaces in C#

The always creative Bevan Arps demonstrates a neat prototype which uses the C# dynamic keyword to provide a concise and readable way of describing validations within C# code, and asks, “Does this qualify as evil code, or merely expressive?”

Well, it’s clearly expressive.  And languages like Ruby use this kind of idiom all the time, so it’s clearly not evil.  But there is something about it (and about some related code I demoed at TechEd) which might reasonably make you feel a bit doubtful.  It’s not evil per se, but is it un-C#-ish?  C# is traditionally a statically typed language, which encourages reliance on the compiler to check correctness: are Ruby-ish idioms simply inappropriate?

Idioms evolve with the language; or, rather, what is idiomatic develops from what people do with language features.  Take C# anonymous types.  They were initially designed to simplify writing LINQ projections, with the expectation that the results would be consumed in the same method where the anonymous type arose.  Maybe you could data-bind to them if you felt adventurous.  Then somebody realised that anonymous types made a really handy syntax for a set of key-value pairs – basically a dictionary, but without all the tedious overhead of C# dictionary literals.  An idiom was born: anonymous types are now firmly established as the C# equivalent of Ruby hashes.

So it is with dynamic.  ASP.NET MVC 3 uses a dynamic ViewBag to shield developers from the rather mild horrors of dictionary access syntax.  Libraries like Dapper, which uses dynamic properties to sweeten what would otherwise be a .NET 1.0 DataTable, are entering the vocabulary of the C# community.  People like Bevan are finding cases where dynamic interfaces enable them to write shorter, cleaner and more expressive code.  It may be unsafe, sure, but typically no more unsafe than the literal strings it often replaces.

Right now, using dynamic interfaces in C# does feel a bit weird.  And there’s no doubt that most C# code and APIs will remain statically typed and compiler verified.  But dynamic interfaces are clearly becoming part of the idiom: the question is not whether dynamic interfaces belong in C#, but where they belong and how much we should use them.

September 1, 2011 in Software | Permalink

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/services/trackback/6a00d8341c5c9b53ef014e8b263405970d

Listed below are links to weblogs that reference Dynamic interfaces in C#:

Comments