Hawaiʻi's Technology Community

C# 4: Dynamic Types, Variance & Named Arguments

C# 4 adds some great features to what is already this language geek's favorite language. One of the overarching design goals of C# 4 is to be more dynamic. From the docs:
The major theme for C# 4.0 is dynamic programming. Increasingly, objects are “dynamic” in the sense that their structure and behavior is not captured by a static type, or at least not one that the compiler knows about when compiling your program.
Lets take a quick look at C# 4's dynamic keyword, which instructs the compiler to defer binding until runtime.

Before dynamic (using reflection):
object randomizer = GetRandomizer();
Type rtype = randomizer.getType();
object randObj = rtype.InvokeMember("NextInt", BindingFlags.InvokeMethod, null, new object [] {});
int random = Convert.ToInt32(randObj);
With dynamic:
dynamic randomizer = GetRandomizer();
int random = randomizer.NextInt();

Is this just syntactic sugar? Not exactly. Its syntatic sugar plus dynamic IL generation and caching in the CLR. It gives you the flexibility of a dynamically typed scripty language but with much better performance characteristics. Running inside the CLR is already a huge advantage because, like the JVM, its a highly optimized environment with JIT / adaptive compilation and a sophisticated generational garbage collector. Most popular scripting languages simply don't enjoy as powerful a runtime environment.

Question: Doesn't this destroy the type safety and other advantages of static typing? As my doctor once responded to the inquiry, "It hurts then I do this. What should I do?" Doctor: "Don't do that." If you are writing code for a pacemaker, don't use it. There are many situations where more agile language features are useful.

Optional Parameters and Named Arguments
I have been begging for this language feature in Java and C# for years. Java's standard library is easily bloated 20%+ by all the overloaded variants of constructors and utility methods. The Swing library is a perfect example. JOptionPane has seven constructors, each adding an additional parameter. With optional parameters and named arguments it would require one.

A simple constructor using an optional param:
Button(string text, Border border = Borders.DefaultBorder) {
this.text = text;
this.border = border;

var greetButton = new Button("Aloha");
I can specify the border, but if I don't, DefaultBorder will be used. This approach makes APIs and the code that uses them much terser and easier to read.

Invoking a constructor with named arguments:
var label = new Label("Address", Icon: myIcon, Opaque: true);
Nice, eh?

Generic Type Variance
Type variance may not be as exciting, but it really tightens the language. It allows, for example, the assignment of an object with the type IEnumerable to a variable with the type IEnumerable. Interfaces can have their type params marked as covariant or contravariant. With this addition C# has, in my opinion, the best system for handling generic types. Unlike Java, all of these concepts are enforced both by the compiler and the runtime.
Thats it for now. In my next post I'll explore how C# 4's new language features interop with the DLR (Dynamic Language Runtime.) If you want more details about C# 4, take a look at Microsoft's New Features in C# 4.0.

Ikayzo - Design • Build • Localize | Web • Desktop • Mobile

Views: 415


You need to be a member of TechHui to add comments!

Join TechHui

Comment by Konstantin A Lukin on November 10, 2009 at 9:10pm
Yep, LINQ like syntax would be a great addition to the Groovy family :)
Comment by Daniel Leuck on November 10, 2009 at 4:32pm
Hi Kostya - Groovy has some nice language features. We would love to see a post about it.

I implemented named argument support in BeanShell almost 10 years ago, but never released it as Pat thought it strayed too far from the Java language spec (which it did.) I really should have forked the project and given the language a new name, but I didn't have the hours to release and support a new language. Now the Groovy guys beat me to it :-)

Last year I wrote a post about how you can add named arguments to the Java grammar using JJTree and JavaCC.

re: Your example of searching on a property:
def quote = Quote.findByAuthor("Larry Wall")

C#, via LINQ, has a complete query language fully integrated into its grammar. Example:
    List products = GetProducts();
var goodBuys =
from p in products
where p.UnitsInStock > 0 && p.UnitPrice < 5
select p;

...and the whole thing is fully understood by the compiler and strongly typed. Nice eh?
Comment by Konstantin A Lukin on November 10, 2009 at 2:39pm
Being an aspiring programmer, I've noticed some very nice language constructs, and couldn't help but to reflect with possible Groovy alternatives.. For example:

In groovy constructor, one can do the following:
randomQuote = new Quote(author: "Anonymous", content: "Real Programmers Don't eat Quiche")

In Grails, it is possible to do things like:
def quote = Quote.findByAuthor("Larry Wall")

Or (notice 'save()' at the end of the clause)
new Quote(author: 'Chuck Norris Facts', content: 'Chuck Norris always uses his own design patterns, and his favorite is the Roundhouse Kick').save()

Though I am just getting up to speed with Groovy/Grails, someday would like to make a post about most notable features and how they help to solve common problems/tasks. Nevertheless, Groovy/Grails surely feels like a step forward compared to good old Java syntax along with manual xml configurations, etc..
Comment by Daniel Leuck on October 26, 2009 at 7:24am
I has been interesting watching ActionScript evolve into what is more or less a Java dialect.

C# started life as Java with boxing/unboxing and language level support for events and properties. Boxing / unboxing made its way back into Java, and with Java 7 a number of other C# language features are being added. C# 3 added some very interesting features, most notably LINQ. I think Java would greatly benefit from LINQ as well as the C# 4 features described above.

I like some of the language features being added in Java 7 such as annotations on types, but they aren't doing anything really innovative.
Comment by Pat Niemeyer on October 25, 2009 at 4:32am
These look very useful. ActionScript has the dynamic invocation features of course, since it's crawling up to static types from being purely dynamic. It also has the optional and named parameters in exactly the same way. What it is lacking is the generic types.

It is really interesting how all of the sort of post-Java languages are converging on a similar point with more or less Java syntax but the same handful of powerful additional features.


web design, web development, localization

© 2020   Created by Daniel Leuck.   Powered by

Badges  |  Report an Issue  |  Terms of Service