Get Ready For C# 4.0!

Get Ready For C# 4.0!

Rate This
  • Comments 70

Visual Studio 2010 is here! And of course this means that C# 4.0 is also here. Let’s do a quick review of the new language features added in this release.

Dynamic

The dynamic keyword is a key feature of this release. It closes the gap between dynamic and statically-typed languages. Now you can create dynamic objects and let their types be determined at run time. With the addition of the System.Dynamic namespace, you can create expandable objects and advanced class wrappers, and you can provide interoperability between different languages, including dynamic ones. Here is one quick example:

dynamic contact = new ExpandoObject();
contact.Name = "Patrick Hines";
contact.Phone = "206-555-0144";

I have discussed the pros and cons of this feature on this blog. If you want to know more, read here.

Covariance and Contravariance

Variance on generic type parameters in interfaces and delegates is another important feature of this release. It doesn’t add much new functionality, but rather makes things work as you expected them to in the first place. The major advantage is hidden in this simple line, which didn’t compile until C# 4.0:

IEnumerable<Object> objects = new List<String>();

The ability to implicitly convert references for objects instantiated with different type arguments makes it much easier to reuse code. Read the Covariance and Contravariance FAQ to learn more about this feature.

Optional (or Default) Parameters

Looking at the archives of this blog, I see that people have been asking for this feature since C# 1.0. Three versions later, it’s finally here.

Now you can assign a default value to a parameter right within the method declaration. The user of the method can either pass a value or simply skip the argument. In the latter case, the default value is passed to the method.

Method declaration:

public static void SomeMethod(int optional = 0) { }

Method calls:

SomeMethod(); // 0 is used in the method.
SomeMethod(10);

Named Arguments

The order of parameters in a method declaration and the order of arguments you pass when calling the method don’t need to match anymore. You can provide arguments in any order you like by specifying parameter names in a method call. This might also improve the readability of your code.

var sample = new List<String>();
sample.InsertRange(collection: new List<String>(), index: 0);
sample.InsertRange(index: 0, collection: new List<String>());

Read more about optional parameters and named arguments on MSDN.

Improved COM Interop

The introduction of the dynamic keyword, optional parameters and named arguments enables improvement of COM interop. So, no more ugly code like this:

var excelApp = new Excel.Application();
// . . .
excelApp.get_Range("A1", "B4").AutoFormat(
    Excel.XlRangeAutoFormat.xlRangeAutoFormatTable3,
    Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, Type.Missing, Type.Missing);

You can now simply write the following:

excelApp.Range["A1", "B3"].AutoFormat(
    Excel.XlRangeAutoFormat.xlRangeAutoFormatClassic2);

By the way, this code uses one more new feature: indexed properties (take a closer look at those square brackets after Range.) But this feature is available only for COM interop; you cannot create your own indexed properties in C# 4.0.

For more information about new COM interop features, once again, refer to MSDN.

What Else?

Of course, C# benefits not only from new language features, but also from improvements to its integrated development environment (IDE) and to the .NET Framework.

Here are some links for further reading:

Happy coding, and thanks to all of you who helped to make this release better by providing feedback!

Leave a Comment
  • Please add 1 and 2 and type the answer here:
  • Post
  • Jakman: couldn't agree more with you.

    At the end of the day, it means that you and I have to enforce our coding conventions and teach the kids that if they write code like this, they're out.

  • Jakman said on April 27, 2010 2:50 PM:

    "Optional Parameters.. So now the amateurs can avoid learning how to overload their methods.. "

    A method with five optional parameters, implemented with overloading, would require 2^5 = 32 overloads - that's assuming that every parameter is of a distinct type or else overloading won't even be capable of solving this. Furthermore at the call site it would be extremely difficult to figure out which parameters were being specified. By taking advantage of named/optional parameters, only a single method definition is needed and it is always obvious from the call site which parameters are being specified, and it is guaranteed that the same method implementation will be used.

    Even an "amateur" should be able to see the advantage of this... :)

  • Named parameters are great, but optional parameters are useless and only add to versioning headaches because those optional parameters are, as you guessed it, baked in as constants to client code. This only serves to increase the  surface area of what should be considered breaking changes.

    Using overrides, library code 'defaults' can at least be altered without affecting client code. I also don't see any reasonable circumstances where a decently written API benefits in the slightest. Large numbers of parameters, like too many overrides, are a bad code smell, so lets throw gas on the fire with optional parameters.

    It's more and more apparent that unless changes are hopelessly trivial, you should recompile everything.

  • Hello, you are recommending us to report any problems to Microsoft Connect. Well, I've reported a bug by 2 months by now and have received no answer yet... Is there anybody looking at it?

  • Hi Hamilton, what's the Connect ID?

    Thanks!

    Kirill Osenkov

  • What happens to type safety with DLR and dynamic?

    Wasn't typesafety C#'s key benefit?

  • As I read this I have to agree with others. This is starting to look like VBC#. Is that the intent? How much slower is this going to make it? C# is already slow when compared to C++

  • Is the dynamic & optional is really required?!, I guess this obviously leads into lack of performance of C#, We could already feel that C# apps working bit slower than the app made in Java / C++.

  • 2 ChicagoBob & Jagadeesan Kandasamy

    As for performance, DLR has a very really clever caching, so sometimes using dynamic for interop might be faster than relying on reflection. If you don't use dynamic, your performance should not be affected.

    You can read more about DLR performance here: http://dlr.codeplex.com/

    The team published all the specs online.

  • Bob said: "optional parameters are useless"

    Attention getting statements that are patently false cause readers to ignore whatever else you might say.

    He also said:  "At the end of the day, it means that you and I have to enforce our coding conventions and teach the kids that if they write code like this, they're out."

    Please don't hurt yourself getting off of that high horse.

    He also drones on and on with: "We've already established from other blog entries that dynamic, expando and named arguments are bad things and should be avoided at all costs"

    Speak for yourself.  And preferably with less childish hyperbole.  Many people disagree that they are Bad Things -- making blanket statements of unqualified rejection does not make you look wise.

  • Cool. C# is beginning to catch up with Smalltalk.

  • I'm more of a Fortran 9X guy so please by patient with me ^_^.

    These optional arguments look more like default arguments to me.  How would you declare an optional argument of a dynamically allocated array, for example?

    I had heard nothing negative about either named or optional arguments until I read this blog.  Could someone point me toward some discussion about these?  My Fortran 90/95 codes use them heavily and I haven't had any maintenance or readability problems yet.

  • PS:

    In Fortran 9X, named and optional arguments are connected.  If I have:

    SomeMethod(int optional = 0, int optional = 1){}

    ...

    SomeMethod(10);

    which variable is set to 10 is ambiguous.

    Thank you in advance for your patience ^_^.

  • @CSharpner

    Obviously, you need to learn a bit about Excel spreadsheet engineering and its importance in the business world to seamlessly interact with Line of Business Applications.  

    .NET datagrid might meet your requirements as a code monkey, but not for 90% of the information systems workers that need to put knowledge behind the data.

    Cheers to COM Interop

  • @ Tamino

    It's essentially the same idea in C#. I just tried to highlight a use case, where named parameters might be useful even without optional parameters. The scenario when you combine optional and named parameters is well-known and well-documented.

    As for negative comments - yes, I am very light on moderation here. I only delete comments that are too personal or use inappropriate language.

    As far as I know, almost any new feature gets at least some negative feedback (and I am not speaking about just languages or even just Microsoft here). This negative feedback varies from implementation specifics to general comments like "Ha! This is what you spend your precious time on instead of fixing bugs!" and "With all these new features your product is now too bloated and heavy, I liked it more when it had just a couple of features."

    So, I am personally OK with negative feedback, especially when it generates a useful discussion.

Page 3 of 5 (70 items) 12345