16 tháng 5, 2010

C# 4.0

Main reference at: http://msdn.microsoft.com/en-us/vcsharp/ff628440.aspx

The great feature introduced in C# 4.0 is dynamic programming which is also presented in MSDN lately. And some other new features:
  • Named and optional parameters
  • Variance
How named and optional parameter feature works

The C# compiler supports this feature and the runtime have no idea about named and optional parameter at all. The main idea is that the default value of parameter is transformed into attributes which is marked on parameter itself. And when the C# compiler see any invocation using optional or named feature, it will look into the source definition (method, delegate ...) and use info from attributes on optional parameter and then adjust the invocation again.

Below is the sample code using optional feature



And next picture is the disassembled code. It's observed that C# compiler 4.0 generated automatically Optional and DefaultParameterValue attribute on those parameters. And when any invocation to the method DoThing1() occurs, the C# compiler sees these attributes and it knows what value shoud be put to the missing parameter in the invocation.




In nutshell, how to play with covariance and contravariance

Look at below code snipe

Covariance
IList<Stream> streams = new List<FileStream>();


Contravariance
IList<FileStream> streams = new List<Stream>();

And the reason why this magic can happen are available on net. But I can understand it in this way: two these features allow us to cast generic interface or method to relative its subclass or superclass.

And dynamic

dynamic gives C# wings to make it more stronger. Before NET 4.0, C# is statically typed language. Now with Dynamic Language Runtime (a bunch of new API) and C# 4.0 compiler, you can use coding JavaScript style happily in C#.

Here is summary: dynamic is a type. That means I can declare a variable /property / parameter with type dynamic, return a type dynamic in method / property ... I'm even able to use dynamic with some operators like as , is . The distinct feature of dynamic type is that all operators / invocations on dynamic type isn't checked in compiled-time, it's done in runtime. That's all.

Reference for dynamic:

Không có nhận xét nào:

Đăng nhận xét