Get Ready For C# 4.0!
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:
- Find all calls to and from your methods with the new Call Hierarchy window.
- Even if you have never heard of test-driven development (TDD), the Generate From Usage feature may help you to quickly prototype your application by generating method and class stubs, allowing you to concentrate on your current task rather than worrying about declarations. For TDD adepts, this feature might be a real performance booster. Check out this walkthrough for more details.
- Don’t forget to take a look at What's New in the .NET Framework 4 and also at What's New in Visual C# 2010 (just to make sure I didn’t miss something).
- And just in case, check out breaking changes for C# and .NET Framework.
- Last, but not least, don’t forget to report any problems at Microsoft Connect.
- Update. See my new post: New IDE Features in Visual Studio 2010 for C# Developers.
Happy coding, and thanks to all of you who helped to make this release better by providing feedback!
Comments
Anonymous
April 14, 2010
The dynamic keyword also allows for multiple method dispatch or advanced polymorphism and can also be a replacement for Reflection. These concepts are explored in this article <a href="http://www.i-programmer.info/programming/72-theory/604-type-systems-demystified.html?start=3">Type Systems Demystified</a>, which also explains the difference between the dynamic and object typeAnonymous
April 15, 2010
I really like the ability to default parameters:D One of the most missed feature of c++, for me.Anonymous
April 20, 2010
Optional Parameters feature is cool....Anonymous
April 20, 2010
dynamic keyword is great in useAnonymous
April 20, 2010
I see that C# is finally catching up with VB ;-)Anonymous
April 20, 2010
Please fix a typo Covariance and Covariance FAQ should be Covariance and Contravariance FAQAnonymous
April 21, 2010
@partha Thanks, fixed.Anonymous
April 21, 2010
any word on whether datasets support nullable types yet in 4.0?Anonymous
April 21, 2010
Named Arguments?! unbeliveable!!Anonymous
April 21, 2010
Optional parameters!! At LAST!!! The built in support for memory mapped files (not mentioned above) is also another brilliant addition. C# 4.0 is looking truly fantasitc.Anonymous
April 21, 2010
Can't wait for 4.0. optional params at last!Anonymous
April 21, 2010
I'm not so sure about Named Arguments. Re-arranging defined parameter orders and adding labels to parameter lists doesn't make more readable code for me. In fact I see huge abuses of this functionality that could make it much less readable.Anonymous
April 22, 2010
C# is supposed to be a standardized language that's not specific to a particular platform (like Windows). It's clear that this dynamic keyword was added /mostly/ for COM interop... A Windows Only feature. COM will go away one day. COM doesn't exist on any other platforms that DO support C#. You don't modify a language because of ONE old and fading feature of ONE O/S. This feature seriously degrades the language and it absolutely, positively, WILL, beyond the shadow of ANY doubt, be abused rampantly, not just by bad coders, but by NEW coders as well as cross-coders (coders who's expertise is in other, dynamic languages). Our public resources of C# code will now start being filled with poorly written code that abuses this feature. This makes it ALL of our problem. It's not a matter of whether WE choose to use the dynamic feature or not, it's a matter of everyone existing in the same "ecosystem" where we're going to HAVE to deal with maintaining poorly written code that abuses this feature. I rejoiced when I no longer had to deal with "variant". This was a HORRIBLE decision and a poorly made one at that.
Aside from that (and that's a HUGE "aside"), the other features I've seen are awesome and I'm already using some of them, but I do regret the decision to include "dynamic" because I -=>KNOW<=- how badly it's going to be abused. Please people, AVOID using dynamic types UNLESS you're using COM interop. Actually, I'd prefer that NOBODY used it for ANY reason to improve the chances of them ripping this monster out of a later language update. I can't believe that ECMA would have accepted this feature into the language! ARGH!
Anonymous
April 22, 2010
Covariance and Contravariance - Eureka!!!Anonymous
April 22, 2010
The comment has been removedAnonymous
April 22, 2010
@ 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)Anonymous
April 22, 2010
@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.Anonymous
April 22, 2010
@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.Anonymous
April 22, 2010
@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.)Anonymous
April 22, 2010
This is really a .Net 4.0 feature but still huge for c# developers - Tuples!!Anonymous
April 22, 2010
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.Anonymous
April 22, 2010
The comment has been removedAnonymous
April 22, 2010
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?Anonymous
April 22, 2010
The comment has been removedAnonymous
April 25, 2010
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.Anonymous
April 26, 2010
para que fecha sale c# 4.0 en españolAnonymous
April 26, 2010
C# 4.0 Is a Powerfull Tool. Great :PAnonymous
April 27, 2010
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.Anonymous
April 27, 2010
@ 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.aspxAnonymous
April 27, 2010
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.Anonymous
April 27, 2010
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.Anonymous
April 27, 2010
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... :)Anonymous
April 28, 2010
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.Anonymous
April 29, 2010
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?Anonymous
April 29, 2010
Hi Hamilton, what's the Connect ID? Thanks! Kirill OsenkovAnonymous
April 29, 2010
What happens to type safety with DLR and dynamic? Wasn't typesafety C#'s key benefit?Anonymous
April 30, 2010
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++Anonymous
May 02, 2010
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++.Anonymous
May 03, 2010
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.Anonymous
May 04, 2010
The comment has been removedAnonymous
May 05, 2010
Cool. C# is beginning to catch up with Smalltalk.Anonymous
May 06, 2010
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.Anonymous
May 06, 2010
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 ^_^.Anonymous
May 06, 2010
The comment has been removedAnonymous
May 06, 2010
@ 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.Anonymous
May 06, 2010
@ Alexandra Rusina Thank you for your quick reply ^_^. I just wanted to make sure that these features didn't have some issues that I wasn't aware of. In C#, how would I declare an optional paramter of struct or a dynamically allocated array?Anonymous
May 06, 2010
C# is getting beter but as all professional can get is that all microsoft will get all benefits from all programming languages to get final & Powerfull C# language. Eidivandi@live.com MCPD -Anonymous
May 06, 2010
The comment has been removedAnonymous
May 06, 2010
@ Tamino Here is what I've got from C# team: "Optional parameter of a struct type S is allowed. The only default argument you can specify is default(S). You cannot specify dynamically allocated arrays. (they cannot be represented in metadata). You can of course specify null as the default argument for an array, and then allocate an array in the method body when that argument is null. But you cannot know if the null was explicitly passed in the call, or results from an omitted argument." So, the answer is yes, they are allowed, but not very useful in these scenarios. @ Eidivandi I'd recommend to ask such questions at MSDN forums. Here is the one for WPF: http://social.msdn.microsoft.com/forums/en-US/wpf/threads/Anonymous
May 06, 2010
@ Alexandra Thank you for the response ^_^. Being unrepresentable in metadata doesn't sound encouraging for future support. Is this the reason why no .NET version of either Fortran 9X or Fortran 2003 is on the horizon? But at least the basic datatypes can be optional now so this is still a step forward.Anonymous
May 06, 2010
I agree with @CSharpner. Personally, I think one of the cool features of C# as opposed to other languages is its structured approach to programming and therefore i dont like the dynamic keyword. Having also used c++, I have to say that I do not like the optional parameters addition either.Anonymous
May 08, 2010
The comment has been removedAnonymous
May 09, 2010
Hello. Probably, I am missing something very very fundamental here, but I was shocked to see the following statement in your post: "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." I tried compiling a small class having indexers with the C# 4 compiler that was shipped with VS 2010 beta and I could use the indexers just as I can with the earlier versions of C#. Then, what's changed? Kindly clarify my confusion. Thank you!Anonymous
May 09, 2010
I want to know how to use operators like +, -, / or * with Generic Classes in C# 4.0Anonymous
May 09, 2010
Isn't it about time Microsoft provided a decent .NET wrapper for Excel (and the rest of Office) so we don't need to guddle about in COM interop at all?Anonymous
May 10, 2010
@ Tamino As far as I know, Fortran is not a Microsoft language. I can't say anything about it. @Pankaj Sharma These are two different features: indexers and indexed properties. You can always have myObject[0]; but here is a different scenario - myObject.MyProperty[0]; This is supported for COM interop only. @Bobby Sorry, but I am not sure I understand your question. Can you please provide a code example of what you are trying to do? @Robert This is probably what you should file at Microsoft.Connect: https://connect.microsoft.com/VisualStudio?wa=wsignin1.0Anonymous
May 10, 2010
Starting to look more and more like c++. Why not just skip c# and use c++ insteadAnonymous
May 10, 2010
The comment has been removedAnonymous
May 11, 2010
I have to agree with Csharpner to a large degree. Optional parameters makes code difficult to read and maintian if you were not the one to write it originally. If you have a large number of parameters for a method, you probably have a method that is doing to much and really should be refactored into several smaller methods. This is a bad code smell. I understand that COM interop has many instances of this showing up especially when working with Excel. I still would have to recommend against using this with your own code that is not COM. As far as dynamic goes and variant for that matter, this is useful in a limited circumstance as well. If you are writing code that does not rely on interoperating with dynamically typed languages, you should avoid using this feature. C# was designed to be a strongly typed language cousin of VB NOT to be VB written a little differently. Good programming practice should be to know what types are going in and out and around your program. There is a great opportunity for dynamic to be misused/abused so you don't have to think about what you are doing. Bad practice. I understand that both of these additions have their place, but I also believe that their place is very narrow and should be kept that way. Shortcuts to get a job done quickly rarely lead to maintainable code or easily debugged code. Proper forethought and design are essentia to professional, maintainable code. Dumbing down C# is likely to lose support of many highly trained professional developers as we will not want to have to fix the broken mess created by shortcut programmers.Anonymous
May 11, 2010
Some of these features seem pretty neat. But I wonder if there will be new controls in the GUI toolbox for Visual Studio.Anonymous
May 11, 2010
I enjoy C# programming, I wonder what else may be added to new versions. i think it is already a full answered for every project, but i bleive in future.Anonymous
May 11, 2010
i hope dynamic will not break the existing code. when i have a class with name dynamic, which works well with .net 2.0Anonymous
May 12, 2010
@ CodeSlinger We are in a planning stage still, so it's hard to tell what the plans for the next version are. Again, I'd recommend to go to Microsoft Connect. Probably, this is something similar to what you are talking about: http://connect.microsoft.com/VisualStudio/feedback/details/94264/arithmetic-types-like-int-double-decimal-should-implement-iarithmetic-t Vote for the issue and leave your comments, so the team can answer you. There is a really long discussion there already. @fallu "dynamic" is a contextual keyword. It means that it's not reserved, so you can use it as a class or class member name.Anonymous
May 12, 2010
Yes, Default Paramater... FINALLYAnonymous
June 01, 2010
Really Cool... C# 4.0 will rock. I really like the dynamic keyword feature of this language as well as COM interop.Anonymous
June 02, 2010
I wonder why it took sooooo long to add optional and named parameters in C#? Why was not included in the C# 1.0?Anonymous
June 03, 2010
Yes. Finally, optional parameter.Anonymous
July 12, 2010
Dynamic features is very interesting and very good...Anonymous
December 04, 2010
Can you start form zero? Because me is newbie,,, http://ifqo.wordpress.comAnonymous
July 03, 2014
dynamic contact = new ExpandoObject(); contact.Name = "Patrick Hines"; contact.Phone = "206-555-0144";