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:
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:
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:
Method calls:
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.
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:
// . . .
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:
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!
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 type
I really like the ability to default parameters:D One of the most missed feature of c++, for me.
Optional Parameters feature is cool….
dynamic keyword is great in use
I see that C# is finally catching up with VB 😉
Please fix a typo
Covariance and Covariance FAQ should be Covariance and Contravariance FAQ
@partha
Thanks, fixed.
any word on whether datasets support nullable types yet in 4.0?
Named Arguments?! unbeliveable!!
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.
Can’t wait for 4.0.
optional params at last!
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.
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!
Covariance and Contravariance – Eureka!!!
Mr C Sharpner is making some rather ignorant statements. For one, the "dynamic" functionality has existed in VB.Net since V1.0. Although VB.Net uses the idea of late binding using "option explicit off", it is the same thing. Therefore, doing COM interop was much easier in VB.Net and it did not in itself cause major problems. I personally worked on VB.Net projects and we always used option explicit except where COM interop was needed, where we would turn it off. Until C# added the "var" type, it was extremely difficult to do work with certain COM types that did not export thier types correctly.
Secondly, the complaint that it somehow pollutes the C# language for other platforms shows an ignorance of the real world of software. Microsoft makes C# for Windows and that’s where it is going to provide support and features. There is a need for COM interop, and for WinAPI (Pinvoke) support. Nearly all C# code is written to run on Windows, except for the half a dozen or so programmers who are using Mono.
@ 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 😛
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.
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.
@ 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?
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 –
i m looking for benefits of WPF but what i have catched is so that this is not enough for begin a large project ,
and 1 question for my test example is that i cant move the label control in the canvas layout control
plz help me ,
@ 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/
@ 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.
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.
The dynamic keyword kan be very handy. I agree that it may cause lots of bad stuff, but those that abuse the dynamic keyword shouldn’t be coding in the first place at all as only crappy coders would abuse it.
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!
I want to know how to use operators like +, -, / or * with Generic Classes in C# 4.0
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?
@ 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.0
Starting to look more and more like c++.
Why not just skip c# and use c++ instead
Any chance we’ll be getting some way of having numeric types as a constraint on generics?
e.g:
public class Foo<T> where T:Numeric{}
so that we can make, say functions that expect T to contain math operators? (I think this is sort of what Bobby was asking)
Would also be nice to be able to say what types are NOT desired in constraints 😀
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.
Some of these features seem pretty neat. But I wonder if there will be new controls in the GUI toolbox for Visual Studio.
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.
i hope dynamic will not break the existing code.
when i have a class with name dynamic, which works well with .net 2.0
@ 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.
Yes, Default Paramater… FINALLY
Really Cool… C# 4.0 will rock. I really like the dynamic keyword feature of this language as well as COM interop.
I wonder why it took sooooo long to add optional and named parameters in C#? Why was not included in the C# 1.0?
Yes. Finally, optional parameter.
Dynamic features is very interesting and very good…
Can you start form zero? Because me is newbie,,,
http://ifqo.wordpress.com
dynamic contact = new ExpandoObject();
contact.Name = "Patrick Hines";
contact.Phone = "206-555-0144";