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 4 and 8 and type the answer here:
  • Post
  • @ setiri

    Sorry, didn't hear anything about nullable types for datasets...

    @Stephen York

    This is the .NET feature, not C# language's one (I know, it's hard to make a distinction sometime). It is in fact mentioned in "What's New in the .NET Framework 4" doc (http://msdn.microsoft.com/en-us/library/ms171868%28VS.100%29.aspx)

  • @Joseph

    Named arguments help a lot when you combine them with optional parameters. If you have several optional parameters of the same type and want to specify only one of them - this is when the named arguments are really essential.

  • @CSharpner

    COM interop is just one interop example where improvemets were made possible due to dynamics. Anders made his first presentation of dynamics at PDC using JavaScript as an example. Interop with dynamic languages is very important scenario. IronRuby and IronPython can interop with C# becuase of DLR and dynamic.

    So, no, it's not *just* for COM, but COM interop was one of the most painful points and it had to be modified first.

  • @CSharpner - I've got 2 words for you: code reviews. Most development teams should do them. You can still use the goto keyword to, but that doesn't mean it is abused (or even used for that matter) by a bunch of developers. The dynamic keyword is a very helpful addition to the framework for many developers (other than just for COM interop.)

  • This is really a .Net 4.0 feature but still huge for c# developers - Tuples!!

  • Regarding j-dub and "code reviews". Please keep in mind that vast amounts of code are developed by overtasked teams with no time for even basic regression test development. When working for gov't projects especially I see absolutely no code reviews of any value taking place. Just cuz something should happen doesn't mean it ever will.

  • B Sharpner,

    No point in stooping down to your name calling tactic, so I won't bite.  Instead, I'll be /consrtuctive/:  It would be nice to have something like option explicit in C# now and have it ON by default.  THAT, I could live with... just barely.  But, unfortunately, we don't.  VB has always had something like it, but C# hasn't and it's now being introduced as a new feature that people are going to want to play with.  The psychology is different from a language that always had it vs. one the recently introduced it.  And, this comes at a time when dynamic languages are becoming more popular.  I see this open and ripe for abuse.

    You have a right to a different opinion, but name calling just makes you look bad.

    j-dub,  If you reread my statement, you'll see that I already addressed how this problem affects us all, regardless of our own personal actions, so code reviews only help locally, and then, only if you can convince your coworkers who perform code reviews that variants/dynamics should be used only in specific cases.  Again, this problem is larger than what can be handled in code reviews.

    I hope and pray that you're both right.  No one would be more delighted than ME.

  • I'm pleased to leave com behind :-) But dynamic is for intercommuication with Dynamic languages as well, IRuby, IronPython etc

    It's for talking to Excel, yes that uses Com, but can it not be used on Linux to help talk to other Applications via what ever the "inter application communiation" layer that linux uses?

  • @abr - I don't know what government projects you're workign on, but perhaps the lack of code reviews is one reason why many government projects overrun, fail, don't function to spec etc etc. Any good project should have a defined set of coding standards which should state if and how certain features can be used.

    More over there is always time for code reviews, even in the most tight deadlines. I work on a government project that delivers to high levels of quality on time every time, and we audit at every stage of development and every layer of the architecture. We probably audit too much, but then we have a happy client, because they get what they wanted - a functioning application.

    C# 4.0 looks to have some great features, but having only just convinced the TDA to move to .NET 3.5 in the past year I suspect it might be a while before I'll be using it in anger!

  • Upgrading to a new platform can often be an expensive and time consuming task. I would prefer service packs on a year or two basis and major releases at least every 5 years.

    We just have 3.5 up and running and now here comes 2010.

    Optional parameters is not that big a deal to me.. as one stated good programming practices with a defined development protcol with standards exceeds the needs for any shortcuts.

  • para que fecha sale c# 4.0 en español

  • C# 4.0 Is a Powerfull Tool. Great :P

  • So, C# is looking more and more like VB.  And this is an improvement how?  Optional Parameters.. So now the amateurs can avoid learning how to overload their methods..  Named Parameters are new?  order is optional?  and this makes the code more readible how?  there is a reason I left VB behind and now here it is.. why have c# at all?  just dump it and go to VB.NET ... what a mess.

  • @ Jakman

    C# and VB coevolution is now an official strategy. So, yes, C# becomes more like VB and at the same time VB becomes more like C#.

    There is a very good blog post from Scott Wiltamuth about this strategy:

    http://blogs.msdn.com/scottwil/archive/2010/03/09/vb-and-c-coevolution.aspx

  • We've already established from other blog entries that dynamic, expando and named arguments are bad things and should be avoided at all costs

    But covariance and optional method params were long overdue.

Page 2 of 5 (70 items) 12345