Archive

Archive for February, 2009

Improving the blog

February 10th, 2009

I’m trying to improve the content of the blog, so I added 3 new and so far quite incomplete sections:

It’s also a way of organizing the content in a better way and saving links to the stuff I like without cluttering the blog (I hate posts that just link to other’s people work or content). I hope it can be useful for some of you out there. See you next time!

Julián Hidalgo Uncategorized

The New Features in C#4

February 9th, 2009

I finally watched the talk about the future of C# that Anders Hejlsberg presented at the last PDC. I had previously read a short paper about the new features in C#4 and a couple of posts by Eric Lippert (look for the five parts series called “The Future of C#”), so I knew about most what he was talking about, but he helped me to understand the whys and to put everything in perspective.

Each C# version’s feature set has been centered on a theme, which helps to prioritize the proposals and to focus the development efforts. So far we’ve had:

  • C# 1.0: Managed code (that is, creating a compiler for managed code)
  • C# 2.0: Generics
  • C# 3.0: LINQ

Of course, in practice there are always features that don’t fit well within the major theme of a version (for example anonymous methods have nothing to do with generics, partial methods had nothing to do with LINQ, and so on). I suggest you to read this post by Eric Lippert to see his slightly different point of view about this topic. For C# 4.0 the theme is dynamic programming (according to Anders, for Lippert it looks more like a “grab-bag”), but what does this mean in terms of features? Here they are:

  • Dynamically typed objects
  • Optional and named parameters
  • Improved COM interoperability
  • Co-variance and contra-variance

According to Lippert, this may seem like a small set of features, and I agree, but he says it was deliberate:

Some feedback that we received loud and clear through the C# 3.0 ship cycle was “this is awesome, we need these language features immediately!” and, somewhat contradictorily, “please stop fundamentally changing the way I think about programming every couple years!” Rather than trying to find some way to yet again radically increase the expressiveness and power of the language, we decided to spend a cycle on making what we already have work better with the other stuff in our programming platform infrastructure.

Let me review each feature in more detail.

Dynamically typed objects

C# 4.0 will allow you “to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the C# static type checking and instead gets resolved at runtime”. This was implemented by introducing a new type called “dynamic“, which under the hoods is just an object type marked with the new Dynamic attribute, so basically we have objects that are statically typed to be dynamic (!). In my opinion this is a clever idea because it flows nicely through the type system, and works well with things like refactoring.

In practice, this means that code that currently looks like this in C# 3.0 (assume the GetCalculator method returns an object whose type is not known at compile time):

 

Could look like this in C# 4.0:

Here the variable calc is statically typed to be dynamic, the invocation of the Add method is dynamic and there’s also a dynamic conversion of the result to an integer. This is more or less what you can do in Visual Basic when you turn off the strict option, the key difference being the new dynamic type. When the operands are dynamic:

  • Member selection is deferred to run-time
  • At run-time the actual type(s) is(are) substituted for dynamic
  • The static result type of an operation is dynamic

I bet this is going to be a controversial feature for many people because after all C# is supposed to be a strongly typed language. Anders himself acknowledged this after presenting the feature: “So now you may go, well, gosh Anders have you gone start driving mad? Haven’t you told us for ten years that static typing is the right and only way, and now you are being heretical?”. I admit I didn’t like it at all at first, but after thinking about it I decided I prefer to maintain 10 lines of dynamic code than 100 lines of reflection based code. If it’s not type-safe then at least I want it to be readable.

If you want to know all the details about this feature I strongly recommend you to read these excellent (and long) series of posts:

Optional and named parameters

A parameter is declared optional by providing a default value for it:

public void MyMethod(int x, int y = 5, int z = 7);

In C# 4.0 you can pass any of those parameters by name, and you can also omit y and z:

MyMethod(1, 2); // omitting z – equivalent to MyMethod(1, 2, 7)
MyMethod(1); // omitting both y and z – equivalent to MyMethod(1, 5, 7)
MyMethod(1, z: 3); // passing z by name
MyMethod(x: 1, z: 3); // passing both x and z by name

I see two big benefits derived from these features (beside the COM thing I mention later):

  • How many times have you seen a method with a boolean parameter like MyMethod(bool closeTheThing)? I don’t know about you, but I always fear to pass the wrong value. If you really care about it (and you own the code) you can always create an enumeration, but it’s quite tiresome. Passing those values by name can really improve the readability of your code with almost no effort (MyMethod(closeTheThing:true)).
  • No more overloads just to make default parameters possible!

Check out this nice post by Sam NG for more details about this feature.

Improved COM interoperability

I don’t care about this too much since I’ve never had to interop with COM that much. The improvements are the following:

  • The optional and named parameters help a lot to improve the COM interop experience. Check out this post by Scott Hanselman to see how a piece of 53 lines of C# 3.0 code that uses the Office Automation libraries is reduced to only 13 lines in VB.NET. The code in C# 4.0 will look just as succinct now.
  • COM’s variant types can now be imported as dynamic.
  • “ref” parameters are now optional.
  • No PIAs: “the C# compiler will bake the small part of the PIA that a program actually uses directly into its assembly. At runtime the PIA does not have to be loaded”.

As you can see, the most important improvements are due to the other new features in the language.

Co-variance and contra-variance

Finally we’ll have some variance support in .NET! I’ve wanted this for a long time so I was quite glad when I heard it would be implemented, but there are a few limitations though. Here are some things to keep in mind:

  • It’s only supported for interface and delegate types (which is disappointing), due to a limitation in the CLR.
  • Technically speaking (that is, from a computer science perspective) they are implementing “statically checked definition-site variance”.
  • Value types are always invariant, so for example IEnumerable<int> is not IEnumerable<object>. This is similar to existing rules for arrays.
  • ref and out parameters need an invariant type.

So how does it work?

  • A co-variant type is signaled with the “out” keyword. It can appear in output positions only, and can be treated as less derived. Example: IEnumerable<out T>.
  • A contra-variant type is signaled with the “in” keyword. It can appear in input positions only, and can be treated as more derived safely. Example: IComparer<in T>.

(Does the “statically checked definition-site variance” thing make more sense now?)

I think the value of this feature can be captured in a phrase that Anders said during the talk: “You’ll be able to do things that you were surprised you couldn’t do”.

C# and VB

Another important announcement made in the talk was that C# and VB will co-evolve from now on, meaning that the same features will be introduced to both of them at the same time (when it makes sense of course). “Co-evolution is the right way to evolve these languages” said Anders, and I think this is totally true. Well, I like the idea of having the VB team copying the features that the C# team introduces, but I’m not so sure if I like it the other way around :)

Highlights of the presentation

Here are a few interesting things that Anders mentioned:

  • There are 3 trends going on in programming: declarative, dynamic, and concurrent.
  • The new paradigm is being multi-paradigm. According to Hejlsberg, C# 3 is already a functional programming language, since it has all the basic features that you need to write functional code (look at Eric Lippert’s definition of a functional programming language: “When I say “functional language”, I mean a language in which it is possible without undue difficulty to program in a functional style”. Not all people would agree with him of course.)
  • There’s a shift from imperative to declarative programming, and lots of talk about DSLs and functional programming.
  • On the dynamic vs. static languages debate, people really want to have the good features from both sides.
  • Concurrency is the elephant in the room. There is no single silver bullet that’s going to fix it and make everything concurrent.
  • The usual problem about concurrency was to make many logical tasks work on fewer CPUs. The new one is making a single logical task run on multiple CPUs.
  • The Parallel Extensions for .NET make great use of all the new functional features in C# 3, allowing them to try out new things without actually commit to a syntax until it has proved to be the right model (I assume this means that at some point in the future the language will be expanded with special constructs for concurrency).
  • Compiler as a service. This is basically about exposing the functionality of the compiler to the programmer, something that’s been tried already in languages like Boo for example. I’m sure it will be a really interesting feature, but first of all they need to write their compiler in managed code (right now it’s coded in C++), which I bet is not a short task. In the talk Anders showed a nice demo, a little interpreter (coded in a couple of lines) that’s able to execute lines of C# code as they are entered, just like the Ruby or Python interpreters we’ve all seen.

OK, that was a long post (I hope it wasn’t too boring). I really suggest you to go watch the presentation and get the CTP. See you next time!

Julián Hidalgo .NET, C# ,