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:

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 = newList<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:

publicstaticvoid 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.

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.

"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:

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.

mlaies

7 May 2010 1:49 AM

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.

Pankaj Sharma

9 May 2010 8:00 AM

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!

Bobby

9 May 2010 11:06 PM

I want to know how to use operators like +, -, / or * with Generic Classes in C# 4.0

Robert

10 May 2010 4:12 AM

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?

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 :D

CSharpFan?

11 May 2010 8:29 AM

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.

Cat Owner

11 May 2010 10:18 AM

Some of these features seem pretty neat. But I wonder if there will be new controls in the GUI toolbox for Visual Studio.