New Cool Features of C# 4.0 [closed]

The dynamic stuff sounds cool if you need it but I don't expect to use it very often.

The generic variance for delegates and interfaces is similar - the lack of variance is a headache at the moment, but many of the places where it's a pain won't be covered by the limited variance available in C# 4.

The COM features don't particularly interest me - I really ought to get more of a handle on what they are though.

Optional and named parameters could make a big difference when building immutable types: it enables syntax like:

Person p = new Person (name: "Jon", age: 32);

without having mammoth combinations of constructor overloads. I'd prefer a bit more support for writing immutable types in the form of readonly automatically implemented properties, but I don't expect we'll get those. (They certainly aren't in the proposed feature list at the moment.)

I'm personally actually more interested in a couple of the framework features of .NET 4.0 - in particular code contracts and parallel extensions.


Method parameter default values:

public void MyMethod1(string value1 = "test", int num1 = 10, double num2 = 12.2)
{
  //...
}

Also maybe anonymous return types:

public var MyMethod2()
{
  // ..
}

Tuples


IDynamicObject, the glue behind dynamic, allows interpretation of a call at runtime.

This is interesting for inherently untyped scenarios such as REST, XML, COM, DataSet, dynamic languages, and many others. It is an implementation of dynamic dispatch built on top of the Dynamic Language Runtime (DLR).

Instead of cumbersome reflection semantics, you dot into variables declared as dynamic. Imagine working with Javascript objects from Silverlight:

dynamic obj = GetScriptObject();

HtmlPage.Window.Alert(obj.someProperty);

All C# syntax is supported (I believe):

HtmlPage.Window.Alert(obj.someMethod() + obj.items[0]);

Reflection itself looks a lot cleaner:

public void WriteSomePropertyValue(object target)
{
    Console.WriteLine((target as dynamic).SomeProperty);
}

public void WriteSomeMethodValue(object target, int arg1, string arg2)
{
    Console.WriteLine((target as dynamic).SomeMethod(arg1, arg2));
}

dynamic is another tool in the toolkit. It does not change the static vs. dynamic debate, it simply eases the friction.


Enhanced support for Expression Trees!