Friday, August 17, 2012

Difference between asp.net versions


Differences between .Net Framework 2.0 and 3.5
Microsoft is always been stepping ahead of its competitors by bringing great new features and products in the market. Specially for developers Microsoft based technologies are like a dream come true. Considering from development point of view the latest product in Microsoft Box is Visual Studio 2008. The new development environment comes with tons of new features and design differences. .Net Framework 3.5 is ready to make futuristic websites with its extremely easy to use interface, rich accessibility features and new design that allows to reduce the time and efforts in website development.
One thing that was lagging in .net framework 2.0 was multi targeting. As in .Net framework 2.0 or framework 1.1 there was a separation in terms of development. Like one builds a site in framework 1.1 would have to use Visual Studio 2003, and for development in framework 2.0 we need to work in Visual Studio 2005. What Visual Studio 2008 has offered a great new experience to target multiple frameworks in one place.
Major advancements have arrived in new framework. Ajax extensions comes built in in .net framework 3.5. Support to place web parts in update panel is also supported.This new built in support has allowed us to create more rich and cross platform Ajax application easier. Apart from this, the extensive set of Ajax templates are also provided in the new framework support. ASP.net 3.5 enhancements for Ajax are totally rewritten for performance and new control types. The existing role management, authentication and authorization are now available as a service. Now we can merge two or more assemblies into one .net assembly with the new .net merge tool. The new controls introduced in Asp.net are LinqDataSource, ListView and DataPager.
Talking of framework 3.5, if is a sequel to framework 3.0, and is the latest in frameworks. Its service pack 1 has been released but it is still not comes in windows server 2008. Microsoft has also release a beta version of Framework 4 and Visual Studio 2010 which is available for download.
One of the major advancement in Framework 3 and 3.5 is LINQ, though we can use LINQ in Framework 2 as well after installing a separate executable, which is now fully supported automatically. Linq allows us to use and interact with data as an object. Now no matter what type of data we have we can play with them using Linq easily. In Figure below we can have an understanding of the architecture of Linq.
http://www.beansoftware.com/ASP.NET-Tutorials/Images/Net-Difference-LINQ.gif
There is rich support for JavaScript coding, debugging, profiling and management in new framework. There is added extended support for JSON, there is design time code validation and checks, also, new design time editor support is provided.
If we have a cross chart of major advancements in framework,
New in .NET framework 2.0
It brings a lot of evolution in class of the framework and refactor control including the support of

Generics
Anonymous methods
Partial class
Nullable type
The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more
Full 64-bit support for both the x64 and the IA64 hardware platforms
New personalization features for ASP.NET, such as support for themes, skins and webparts.
.NET Micro Framework
New in .NET framework 3.0
Also called WinFX,includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems and provides

Windows Communication Foundation (WCF), formerly called Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
Windows Presentation Foundation (WPF), formerly called Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies.
Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
Windows CardSpace, formerly called InfoCard; a software component which securely stores a person's digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website
 
New in .NET framework 3.5
It implement Linq evolution in language. So we have the following evolution in class:

Linq for SQL, XML, Dataset, Object
Addin system
p2p base class
Active directory
ASP.NET Ajax
Anonymous types with static type inference
Paging support for ADO.NET
ADO.NET synchronization API to synchronize local caches and server side datastores
Asynchronous network I/O API
Support for HTTP pipelining and syndication feeds.
New System.CodeDom namespace.
If we take a look into .net Framework 3.0, we clearly see four major break troughs
http://www.beansoftware.com/ASP.NET-Tutorials/Images/Net-Difference-Architecture.gif
Windows Card Space
sWindows card space is a specialized library for identity and authentication. Three main component are Info Card, Digital Identity and Identity Provider. IT provides enhanced security techniques which helps developers to develop more secure and durable websites.
Windows Presentation Foundation
Windows Presentation Foundation or code name Avalon is built for rich media graphics, it is a replacement for windows GDI graphics library. It is a one stop shop for Forms, media, documents and 3d graphics. It is based on XAML (eXtensible markup language) which provides a bridge between developer and graphics designer. Silver Light also uses XAML for displaying its content.
Windows Communication Foundation
Windows Communication foundation or code name Indigo is SOA (Service oriented applications) and built on rich service oriented architecture. The remoting architecture is changed a lot in WCF. WSE 3 introduced with enhance upgrades to Web services. Support of distributed transactions and Message queing are totally rewritten.
http://www.beansoftware.com/ASP.NET-Tutorials/Images/Net-Difference-WCF.gif
Windows Workflow Foundation
It is a workflow foundation for windows based application. It provides both sequential workflows as well as State based workflows. We get a more process oriented view of Software development. Workflows help define the process of an application in a more elite manner.
http://www.beansoftware.com/ASP.NET-Tutorials/Images/Net-Difference-WFC.gif
More notable of point is that .Net 3.5 is not visible in IIS as a separate version, we can just see .Net 2.0 even if there is .Net framework 3.5 installed. Even in windows .Net framework folder, the .Net Framework 3.5 core files reside in .Net framework 2.0 folder and only WPF and WCF libraries are in Framework 3.5 folder. This means that Framework 3 or 3.5 is a wrapper upgrade to Framework 2.0, with support for cross platform and cross framework integration and development.
 
All in all, .Net framework 3.0 and above is lot more enhanced and still getting better for Rich Internet Applications and Service oriented applications. It is keep getting better and better. As Microsoft's passion is our satisfaction.
 

What's New in the .NET Framework 4

The .NET Framework 4 introduces an improved security model. For more information, see Security Changes in the .NET Framework 4. For lists of new namespaces, new types, and new members added to existing types, see New Types and Members in the .NET Framework 4. Other new features and improvements in the .NET Framework 4 are described in the following sections:
·         Parallel Computing
·         Networking
·         Web
·         Client
·         Data
·         Windows Workflow Foundation

What's New in the .NET Framework 4.5 RC
This topic contains a summary of key new features and improvements in the following areas of the .NET Framework 4.5 RC. For general information about the .NET Framework, including guidance for installing or uninstalling the .NET Framework, see Getting Started with the .NET Framework.
·         .NET for Metro style Apps
·         Portable Class Libraries
·         Tools
·         Parallel Computing
·         Web
·         Networking




www.vishnukumarchandel.com

Asynchronous Programming with Async and Await


When you use asynchronous programming, you specify points in your code where potentially long running processes are suspended while other parts of the program can continue. This technique avoids possible performance bottlenecks and enhances the overall responsiveness of your application. Asynchrony is important for activities that are potentially blocking, such as when your program accesses the web. If such an activity is blocked within a synchronous process, the entire program is blocked. In an asynchronous process, the program can make progress in other areas while the blocking task finishes its work.
Asynchrony is especially valuable for processes that access the UI thread because all UI-related activity usually shares one thread. If any process is blocked, all are blocked.
For an example of a blocked process, follow the steps in Walkthrough: Accessing the Web by Using Async and Await (C# and Visual Basic) through the "To test the synchronous solution" section. As an alternative, you can download the code for the walkthrough from Async Sample: Accessing the Web Walkthrough and run the project that’s named SyncWalkthrough. When the UI thread is synchronously downloading content from the web, you can't move or resize the window. You can’t even close it to end the program if you don't want to wait.
The Async (Visual Basic) or async (C#) modifier and the Await (Visual Basic) or await (C#) operator are fundamental to async programming. The async modifier indicates to the compiler that a method or lambda expression is asynchronous and that you can use await operators to designate suspension points within the method. This kind of method is referred to as an async method.
Inside an async method, you can apply an await operator to a particular task to suspend execution of the async method until the awaited task is complete. In the meantime, control is returned to the caller of the async method. The suspension doesn't constitute an exit from the async method, and finally blocks don’t run.
The compiler does the difficult work that the developer used to do, including signing up continuations for the completion of the suspended method. As a result, asynchronous code is much easier to write, and your program retains a logical structure that resembles synchronous code. For example, some routine processes, such as loops and exception handling, can be difficult to write in traditional asynchronous code. In an async method, you write these elements much as you would in a synchronous solution, and the problem is solved. For more information about previous approaches to asynchrony in the .NET Framework, seeTPL and Traditional .NET Asynchronous Programming.
The .NET Framework 4.5 contains many members that work with async and await. You can recognize these members by the "Async" suffix that’s attached to the member name and a return type of Task or Task. For example, the System.IO.Stream class contains methods such as CopyToAsyncReadAsync, and WriteAsyncalongside the synchronous methods CopyToRead, and Write.
The following example illustrates the simplicity of this approach by comparing a method that's written synchronously with the same method if it were written asynchronously. For the full example, see Walkthrough: Accessing the Web by Using Async and Await (C# and Visual Basic).
The following changes convert a synchronous method (GetURLContents) to an asynchronous method (GetURLContentsAsync).
  • Change the method signature in the following ways.
    • Mark the method with the Async or async modifier.
    • Change the return type from Byte() to Task(Of Byte()) in Visual Basic or from byte[] to Task<byte[]> in C#.
      The task is a promise to provide a byte array when the asynchronous process is complete. For more information about async return types, seeAsync Return Types (C# and Visual Basic).
    • By convention, add the suffix "Async" to the method name.
  • In the body of the method, make the following changes.
    • Replace calls to long-running synchronous methods with calls to corresponding asynchronous methods. In this example, replace the call toGetResponse with a call to GetResponseAsync.
    • Apply the Await or await operator to the result of the method call.
    • Replace the call to CopyTo with a call to CopyToAsync.
    • Apply the Await or await operator to the result of the method call.
The conversion is complete. For the full example and step-by-step instructions, see Walkthrough: Accessing the Web by Using Async and Await (C# and Visual Basic).
// Synchronous version of a method that downloads the resource that a URL
// links to and then returns its content.
private byte[] GetURLContents(string url)
{
    // The downloaded resource ends up in the variable named content.
    var content = new MemoryStream();

    // Initialize an HttpWebRequest for the current URL.
    var webReq = (HttpWebRequest)WebRequest.Create(url);

    // Send the request to the Internet resource, and wait for
    // the response.
    using (var response = webReq.GetResponse())
    {
        // Get the data stream that is associated with the specified URL.
        using (Stream responseStream = response.GetResponseStream())
        {
            // Read the bytes in responseStream, and copy them to content.  
            responseStream.CopyTo(content);
        }
    }

    // Return the result as a byte array.
    return content.ToArray();
}


// Asynchronous version of the same method. The changed lines 

//are marked with **.

// **Add the async modifier. Change the method name and the return type.
private async Task<byte[]> GetURLContentsAsync(string url)
{
    // The downloaded resource ends up in the variable named content.
    var content = new MemoryStream();

    // Initialize an HttpWebRequest for the current URL.
    var webReq = (HttpWebRequest)WebRequest.Create(url);

    // **Call GetResponseAsync instead of GetResponse, and await the result.
    // GetResponseAsync returns a Task<WebResponse>.
    using (WebResponse response = await webReq.GetResponseAsync())
    {
        // Get the data stream that is associated with the specified URL.
        using (Stream responseStream = response.GetResponseStream())
        {
            // ** Call CopyToAsync instead of CopyTo, and await the response.
            // CopyToAsync returns a Task, not a Task<T>.
            await responseStream.CopyToAsync(content);
        }
    }
    // Return the result as a byte array.
    return content.ToArray();
}
An async method is modified by the Async or async modifier. The method typically contains one or more occurrences of the Await or await operator, but the absence of await expressions doesn’t cause a compiler error. If an async method doesn’t use an await operator to mark a suspension point, it executes as a synchronous method does, despite the async modifier. The compiler issues a warning for such methods.
Async , asyncAwait, and await are contextual keywords. For more information and examples, see the following topics:
In Visual Basic, an async method is either a Sub procedure or a Function procedure that has a return type of Task or Task.
In C#, an async method can have a return type of voidTask, or Task.
To enable the callers of an async method to await its completion, use a return type of Task or Task. You specify Task as the return type if the method contains aReturn (Visual Basic) or return (C#) statement that specifies an operand of type TResult. You use Task if the method has no return statement or has a return statement that doesn't return an operand.
Sub method (Visual Basic) or a void return type (C#) is used primarily to define event handlers, where a void return type is required. An async method that’s aSub procedure or that has a void return type can’t be awaited, and the caller of a void-returning method can't catch any exceptions that the method throws.
An async method can't declare ByRef parameters in Visual Basic or ref or out parameters in C#, but the method can call methods that have such parameters.
For more information and examples, see Async Return Types (C# and Visual Basic). For more information about how to catch exceptions in async methods, seetry-catch (C# Reference) or Try...Catch...Finally Statement (Visual Basic).
By convention, you add the suffix "Async" to the names of methods that have an Async or async modifier.
You can ignore the convention where an event, base class, or interface contract suggests a different name. For example, you shouldn’t rename common event handlers, such as button1_Click.
Async methods are intended to be non-blocking operations. An await expression in an async method doesn’t block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.
Async methods don't require multithreading because an async method doesn't run on its own thread. The method runs on the current synchronization context and uses time on the thread only when the method is active. For information about how to move async methods or lambda expressions to background threads, see TaskRun.

What is new in Visual Studio 2012


Top 12 of Visual Studio 2012

In case you’re still deciding whether to download Visual Studio 2012, or haven’t been keeping up with all the news about the release, I’ll leave you with 12 good reasons to upgrade today. ;-)

#1) Develop for Windows 8

Visual Studio 2012 contains all the tools you need to develop killer apps for Windows 8, from templates, to designers, to testing, to debugging. Blend now comes with the Visual Studio installation providing rich visual tools for creating Windows store apps using HTML/CSS and XAML. Using these tools, you’ll find everything you need to develop a great app and submit it to the Windows Store.
NewProject
For more information, see the Windows 8 App Developer Blog and the Windows Dev Center.

#2) Develop for the Web

Visual Studio 2012 and .NET 4.5 provide the latest advances in ASP.NET including web optimization improvements (minification and bundling), new templates, HTML & CSS editor improvements, page inspector, and new publishing tools. We’ve added new features to support JavaScript development including IntelliSense improvements, a new DOM explorer, and a JavaScript console. For more information, check out the Web Development team blog.
MvcApplication4 (Running) - Microsoft Visual Studio (10)
Page Inspector

#3) Develop for Windows Phone 8

Visual Studio 2012 will provide support for developing Windows Phone 8 applications (both with a Express SKU as well as a freely downloadable plug-in for VS Pro and above). This will come online in the future, once Windows Phone 8 and the developer SDK become available. Some new features to look forward to include native C++ support, the ability to target both Windows Phone 7.x and Windows Phone 8 applications, multi-chassis support, and enterprise publishing. Stay tuned for more info from the Windows Phone team.
marblemaze_complete_phone
C++ Windows Phone 8 Application

#4) Develop for Windows Azure

Visual Studio provides the best possible tools to develop your cloud services. In Visual Studio 2012, you’ll notice cloud tooling improvements including support for distributed caching, new publishing options, new templates, and a lower install footprint. Using Team Foundation Service with Windows Azure, you can now achieve continuous integration and continuous deployment of your software. For more information, please visit the Windows Azure .NET Developer center, and download today’s release of the Windows Azure SDK for .NET.
Deployed Builds in TFS Portal
Deployment history

#5) Develop Business Applications

Visual Studio 2012 contains a variety of tools for developing business applications. SharePoint developers will find new designers for list and content types, new templates for site columns and Silverlight web pages, as well as new options for deploying SharePoint sites. ALM features like performance profiling, unit testing, and IntelliTrace are now available for SharePoint development. Client-side development has been improved as well, with support for JavaScript debugging and IntelliSense. For more information, please visit the SharePoint developer team blog.
ListDesigner
SharePoint List Designer
Meanwhile, we’ve also announced a new app model for Office and SharePoint 2013, which enables you to host your apps in the cloud, and to use web technologies to develop them. Visual Studio 2012, along with the Microsoft Office Developer Tools for Visual Studio 2012 – Preview, gives you the tools to program with the new app models for Office and SharePoint. To learn more and get started building apps for Office & SharePoint 2013, head to http://dev.office.com.
LightSwitch is a powerful tool available for building business applications for the Desktop and the Cloud. Starting in Visual Studio 2012, LightSwitch is available as part of the Visual Studio Professional, Premium and Ultimate installations. LightSwitch includes a variety of improvements in Visual Studio 2012, such as a new theme, the ability to access data from any OData source as well as create OData services, Active Directory integration, and new business types. We also are working on support for HTML clients, which will be available as an add-on to VS2012. To learn more, please visit the LightSwitch Developer Center and the LightSwitch team blog.
LS
LightSwitch in Visual Studio 2012

#6) Develop Games and other 3D Applications

Visual Studio 2012 includes graphics tools to help game developers become more productive, making it easier to build innovative games. From debugging DirectX graphics, to designing and coding DirectX shaders (HLSL), to inspecting and manipulating graphics assets (images and models), Visual Studio 2012 provides all the functionality you need to build graphically rich 2D/3D applications.
GraphicsImage - Game
Visual Studio 2012 Graphics Diagnostics Tools

#7) Take advantage of the latest language advancements

If you’re developing in C# or Visual Basic, you can take advantage of the language new features in Visual Studio 2012 and .NET 4.5 for asynchronous programming. Using the new async and await keywords, you can write asynchronous code that looks a lot like the synchronous version:
Async
The C++ support in Visual Studio 2012 includes the full C++ 11 standard library as well as new language features: stateless lambdas, SCARY iterators, range-based for loops, and scoped enumerations support. Visual C++ 11 also adds seamless access to Windows Runtime components through C++/CX as well as C++ Accelerated Massive Parallelism (C++ AMP), which enables hardware acceleration for the execution of your data-parallel C++ code.
For JavaScript development, please see more details about the improvements we’ve made in the Web development section above.
Lastly, if you’re using F#, you’ll enjoy improvements for information-rich programming, which enable you to program directly against data services, and are made possible by F# type providers and LINQ queries.

#8) Performance, Reliability, and Compatibility Improvements

In addition to adding new features, we’ve also invested heavily to improve the core capabilities of the product. For example, we’ve invested in performance and made significant improvements in areas such as the toolbox, typing and editing, debugging, and solution loading time.
SolutionLoad
We’ve also taken care to improve the backward compatibility of Visual Studio 2012, and enabled you to continue collaborating on projects with teammates using Visual Studio 2010 SP1.

#9) New IDE Productivity Features

The Visual Studio 2012 user interface includes an updated look and feel, which is consistent with the latest Microsoft products, and designed to focus your attention on the code. The overall environment has been streamlined, including simplified toolbars, a lightweight Find dialog, and less tab clutter by previewing files rather than opening them during debugging. Using Quick Launch, you can now search the IDE for any menu or command.
IDE
New Find Dialog

#10) Improve your code quality with enhanced testing tools

Visual Studio 2012 includes a wealth of testing tools.
Microsoft Test Manager 2012 has been enhanced to embrace exploratory testing (sometimes called agile testing), which allows you to explore the product in any way you want while keeping relevant steps and data that can be used to directly file bugs and feedback:
Exploratory Testing
Lab Management has also been greatly simplified in this release with the consolidation of agents and the introduction of standard environments, which allow you to benefit from build-deploy-test workflows without the dependency on Hyper-V or SCVMM.
With Visual Studio 2012, we now provide the ability for you to include additional adapters to support 3rd party unit testing frameworks such as xUnit.net, NUnit, and others. The new Test Explorer will showcase all of the tests across your solution regardless of which testing framework they were written for. Visual Studio 2012 will continue to provide support for traditional unit tests written using the classic Visual Studio Unit Testing Framework, and adds support for writing tests in C++ as well.
Unit Testing
New Test Explorer

#11) Reduce cycle times using tools for agile practices

Visual Studio 2012 contains a variety of tools to create transparency between team members, reduce waste, and accelerate the flow of the project. As you set out to start the project, PowerPoint storyboarding is a useful way to communicate the requirements of the software. When you get further along, the Microsoft Feedback Client can be used to gather feedback on the working bits from external stakeholders.
Team Foundation Server 2012 provides a rich toolset for planning out your sprints, managing the backlog, and tracking progress. I recommend reading my earlier post, where I explored these features in detail. As an example, below is a picture of the taskboard, which can be used to easily edit work items during a standup meeting:
Taskboard - TFS

#12) Deliver Cloud-Based Services with Smoother Collaboration between Operations and Engineering

Each release of our ALM tools, we’ve integrated additional roles to improve collaboration across the team, and decrease cycle time. This release, we’re including operations, which is increasingly important for today’s cloud-based services apps. Many of you are already using System Center to monitor your applications in production. This release, we’ve introduced a new management pack, which will allow critical production issues detected by System Center 2012 SP1 to be immediately assigned to the development team with high quality diagnostic information via TFS and Visual Studio.
1667.SCOM-TFS_APM_Alert[1]
System Center Operations Manager
These kinds of tools for operations and engineering are something we plan to continue delivering in the future. For example, System Center 2012 SP1 will also introduce “Global Service Monitor” (GSM), which allows you to monitor your application’s functionality, performance, and uptime from multiple endpoints around the world.



www.vishnukumarchandel.com

Thursday, August 16, 2012

Introduction

The major theme for C# 4.0 is dynamic programming. Increasingly, objects are “dynamic” in the sense that their structure and behavior is not captured by a static type, or at least not one that the compiler knows about when compiling your program. Some examples include
·         objects from dynamic programming languages, such as Python or Ruby
·         COM objects accessed through IDispatch
·         ordinary .NET types accessed through reflection
·         objects with changing structure, such as HTML DOM script objects
·         data readers and other user defined dynamic objects
While C# remains a statically typed language, we aim to vastly improve the interaction with such objects.
A secondary theme is co-evolution with Visual Basic. Going forward we will aim to maintain the individual character of each language, but at the same time important new features should be introduced in both languages at the same time. They should be differentiated more by style and feel than by feature set.
The new features in C# 4.0 fall into four groups:

Dynamic binding

Dynamic binding allows you to write method, operator and indexer calls, property and field accesses, and even object invocations which bypass the C# static type checking and instead gets resolved at runtime.

Named and optional arguments

Parameters in C# can now be specified as optional by providing a default value for them in a member declaration. When the member is invoked, optional arguments can be omitted. Furthermore, any argument can be passed by parameter name instead of position.

COM specific interop features

Dynamic binding as well as named and optional arguments help making programming against COM less painful than today. On top of that, however, we are adding a number of other features that further improve the interop experience specifically with COM.

Variance

It used to be that an IEnumerable<string> wasn’t an IEnumerable<object>. Now it is – C# embraces type safe “co-and contravariance,” and common BCL types are updated to take advantage of that.

Dynamic Binding

Dynamic binding offers a unified approach to invoking things dynamically. With dynamic binding, when you have an object in your hand, you do not need to worry about whether it comes from COM, IronPython, the HTML DOM, reflection or elsewhere; you just apply operations to it and leave it to the runtime to figure out what exactly those operations mean for that particular object.
This affords you enormous flexibility, and can greatly simplify your code, but it does come with a significant drawback: Static typing is not enforced for these operations. A dynamic object is assumed at compile time to support any operation, and only at runtime will you get an error if it wasn’t so. Oftentimes this will be no loss, because the object wouldn’t have a static type anyway, in other cases it is a tradeoff between brevity and safety. In order to facilitate this tradeoff, it is a design goal of C# to allow you to opt in or opt out of dynamic behavior on every single call.

The dynamic type

C# 4.0 introduces a new static type called dynamic. When you have an object of type dynamic you can “do things to it” that are resolved only at runtime:
dynamic d = GetDynamicObject(…);
d.M(7);
The C# compiler allows you to call a method with any name and any arguments on d because it is of type dynamic. At runtime the actual object that d refers to will be examined to determine what it means to “call M with an int” on it.
The type dynamic can be thought of as a special version of the type object, which signals that the object can be used dynamically. It is easy to opt in or out of dynamic behavior: any object can be implicitly converted to dynamic, “suspending belief” until runtime. Conversely, expressions of type dynamic can be implicitly converted to object, or indeed any other type, as long as there exists a conversion at runtime:
dynamic d = 7; // compile-time implicit conversion
int i = d;     // runtime implicit conversion

Dynamic operations

Not only method calls, but also field and property accesses, indexer and operator calls and even delegate invocations and constructor calls can be dispatched dynamically:
dynamic d = GetDynamicObject(…);
d.M(7); // calling methods
d.f = d.P; // getting and settings fields and properties
d[“one”] = d[“two”]; // getting and setting through indexers
int i = d + 3; // calling operators
string s = d(5,7); // invoking as a delegate
var c = new C(d); // calling a constructor
The role of the C# compiler here is simply to package up the necessary information about “what is being done to d”, so that the runtime can pick it up and determine what the exact meaning of it is given an actual object d. Think of it as deferring part of the compiler’s job to runtime.
The result of any dynamic operation is itself of type dynamic, with two exceptions:
·         The type of a dynamic constructor call is the constructed type
·         The type of a dynamic implicit or explicit conversion is the target type of the conversion.

Runtime lookup

At runtime a dynamic operation is dispatched according to the nature of its target object d:

Dynamic objects

If d implements the interface IDynamicMetaObjectProvider, it is a so-called dynamic object, which means that it will itself be asked to bind and perform the operation. Thus by implementing IDynamicMetaObjectProvider a type can completely redefine the meaning of operations such as method calls, member access etc. This is used intensively by dynamic languages such as IronPython and IronRuby to implement their own dynamic object models. It is also used by APIs, e.g. by the Silverlight HTML DOM to allow direct access to the object’s properties and methods using member access and method call syntax instead of string-based accessor methods such as SetProperty or Invoke.

COM objects

If d is a COM object, the operation is dispatched dynamically through COM IDispatch. This allows calling to COM types that don’t have a Primary Interop Assembly (PIA), and relying on COM features that don’t have a counterpart in C#, such as default properties.

Plain objects

Otherwise d is a standard .NET object, and the operation will be dispatched using reflection on its type and a C# “runtime binder” which implements C#’s lookup and overload resolution semantics at runtime. This is essentially a part of the C# compiler running as a runtime component to “finish the work” on dynamic operations that was deferred by the static compiler.

Example

Assume the following code:
dynamic d1 = new Foo();
dynamic d2 = new Bar();
string s;
d1.M(s, d2, 3, null);
Because the receiver and an argument of the call to M are dynamic, the C# compiler does not try to resolve the meaning of the call. Instead it stashes away information for the runtime about the call. This information (often referred to as the “payload”) is essentially equivalent to:
“Perform an instance method call of a method called M with the following arguments:
1.       a string
2.       a dynamic
3.       a literal int 3
4.       a literal object null
At runtime, assume that the actual type Foo of d1 is not a dynamic object. In this case the C# runtime binder picks up to finish the overload resolution job based on runtime type information, proceeding as follows:
1.       Reflection is used to obtain the actual runtime types of the two objects, d1 and d2, that did not have a static type (or rather had the static type dynamic). The result is Foo for d1 and Bar for d2.
2.       Method lookup and overload resolution is performed on the type Foo with the call M(string,Bar,3,null) using ordinary C# semantics.
3.       If the method is found it is invoked; otherwise a runtime exception is thrown.

Overload resolution with dynamic arguments

Even if the receiver of a method call is of a static type, overload resolution can still happen at runtime. This will happen if one or more of the arguments have the type dynamic:
Foo foo = new Foo();
dynamic d = new Bar();
var result = foo.M(d);
The C# runtime binder will choose between the statically known overloads of M on Foo, based on the runtime type of d, namely Bar. The result is again of type dynamic.

The Dynamic Language Runtime

An important component in the underlying implementation of dynamic binding is the Dynamic Language Runtime (DLR), which is a new API in .NET 4.0.
The DLR provides most of the infrastructure behind not only C# dynamic binding but also the implementation of several dynamic programming languages on .NET, such as IronPython and IronRuby. Through this common infrastructure a high degree of interoperability is ensured, but just as importantly the DLR provides excellent caching mechanisms which serve to greatly enhance the efficiency of runtime dispatch.
To the user of dynamic binding in C#, the DLR is invisible except for the improved efficiency. However, if you want to implement your own dynamically dispatched objects, the IDynamicMetaObjectProvider interface allows you to interoperate with the DLR and plug in your own behavior. Doing this directly is a rather advanced task, which requires you to understand a good deal more about the inner workings of the DLR. Fortunately .NET 4.0 provides several helper classes to make this task a lot easier, and for API writers, it can definitely be worth the trouble as you can sometimes vastly improve the usability of libraries representing an inherently dynamic domain.

Limitations

There are a few limitations and things that might work differently than you would expect.
·         The DLR allows objects to be created from objects that represent classes. However, the current implementation of C# doesn’t have syntax to support this.
·         Dynamic binding will not be able to find extension methods. Whether extension methods apply or not depends on the static context of the call (i.e. which using clauses occur), and this context information is not kept as part of the payload.
·         Anonymous functions (i.e. lambda expressions) cannot appear as arguments to a dynamic operation. The compiler cannot bind (i.e. “understand”) an anonymous function without knowing what type it is converted to.
One consequence of these limitations is that you cannot easily use LINQ queries over dynamic objects:
dynamic collection = …;
var result = collection.Select(e => e + 5);
If the Select method is an extension method, dynamic binding will not find it. Even if it is an instance method, the above does not compile, because a lambda expression cannot be passed as an argument to a dynamic operation.

Named Arguments and Optional Parameters

Named arguments and optional parameters are really two distinct features, but are often useful together. Optional parameters allow you to omit arguments to member invocations, whereas named arguments is a way to provide an argument using the name of the corresponding parameter instead of relying on its position in the parameter list.
Some APIs, most notably COM interfaces such as the Office automation APIs, are written specifically with named and optional parameters in mind. Up until now it has been very painful to call into these APIs from C#, with sometimes as many as thirty arguments having to be explicitly passed, most of which have reasonable default values and could be omitted.
Even in APIs for .NET however you sometimes find yourself compelled to write many overloads of a method with different combinations of parameters, in order to provide maximum usability to the callers. Optional parameters are a useful alternative for these situations.

Optional parameters

A parameter is declared optional simply by providing a default value for it:
public void M(int x, int y = 5, int z = 7);
Here y and z are optional parameters and can be omitted in calls:
M(1, 2, 3); // ordinary call of M
M(1, 2); // omitting z – equivalent to M(1, 2, 7)
M(1); // omitting both y and z – equivalent to M(1, 5, 7)
Default argument values are somewhat restricted. They must be given as constant expressions, or default value expressions default(T).

Named and optional arguments

C# 4.0 does not permit you to omit arguments between commas as in M(1,,3). This could lead to highly unreadable comma-counting code. Instead if you want to omit arguments in the middle, any argument can be passed by name. Thus if you want to omit only y from a call of M you can write:
M(1, z: 3); // passing z by name
or
M(x: 1, z: 3); // passing both x and z by name
or even
M(z: 3, x: 1); // reversing the order of arguments
All forms are equivalent, except that arguments are always evaluated in the order they appear, so in the last example the 3 is evaluated before the 1.
Optional and named arguments can be used not only with methods but also with indexers and constructors.

Overload resolution

Named and optional arguments affect overload resolution, but the changes are relatively simple:
A signature is applicable if all its parameters are either optional or have exactly one corresponding argument (by name or position) in the call which is convertible to the parameter type.
Betterness rules on conversions are only applied for arguments that are explicitly given – omitted optional arguments are ignored for betterness purposes.
If two signatures are equally good, one that does not omit optional parameters is preferred.
M(string s, int i = 1);
M(object o);
M(int i, string s = “Hello”);
M(int i);
M(5);
Given these overloads, we can see the working of the rules above. M(string,int) is not applicable because 5 doesn’t convert to string. M(int,string) is applicable because its second parameter is optional, and so, obviously are M(object) and M(int).
M(int,string) and M(int) are both better than M(object) because the conversion from 5 to int is better than the conversion from 5 to object.
Finally M(int) is better than M(int,string) because no optional arguments are omitted.
Thus the method that gets called is M(int).

Features for COM interop

Dynamic binding as well as named and optional parameters greatly improve the experience of interoperating with COM APIs such as the Office Automation APIs. In order to remove the remaining speed bumps, a couple of small COM-specific features are also added to C# 4.0.

Compiling without PIAs

Primary Interop Assemblies are large .NET assemblies generated from COM interfaces to facilitate strongly typed interoperability. They provide great support at design time, where your experience of the interop is as good as if the types where really defined in .NET. However, at runtime these large assemblies can easily bloat your program, and also cause versioning issues because they are distributed independently of your application.
The embedded-PIA feature allows you to continue to use PIAs at design time without having them around at runtime. Instead, the C# compiler will bake the small part of the PIA that a program actually uses directly into its assembly. At runtime the PIA does not have to be loaded.

Dynamic import

Many COM methods accept and return “variant” types, which are represented in the PIAs as object. In the vast majority of cases, a programmer calling these methods already knows the static type of a returned object from context, but explicitly has to perform a cast on the returned value to make use of that knowledge. These casts are so common that they constitute a major nuisance.
In order to facilitate a smoother experience, if you choose to import these COM APIs with PIA-embedding, variants are instead represented using the type dynamic. In other words, from your point of view, COM signatures now have occurrences of dynamic instead of object in them.
This means that you can easily access members directly off a returned object, or you can assign it to a strongly typed local variable without having to cast. To illustrate, you can now say
excel.Cells[1, 1].Value = "Hello";
instead of
((Excel.Range)excel.Cells[1, 1]).Value2 = "Hello";
and
Excel.Range range = excel.Cells[1, 1];
instead of
Excel.Range range = (Excel.Range)excel.Cells[1, 1];

Omitting ref

Because of a different programming model, many COM APIs contain a lot of reference parameters. Contrary to refs in C#, these are typically not meant to mutate a passed-in argument for the subsequent benefit of the caller, but are simply another way of passing value parameters.
It therefore feels unreasonable to a C# programmer to have to create temporary variables for all such ref parameters and pass these by reference. Instead, specifically for COM methods, the C# compiler will allow you to pass arguments by value to such reference parameters, and will automatically generate temporary variables to hold the passed-in values, subsequently discarding these when the call returns. In this way the caller sees value semantics, and will not experience any side effects, but the called method still gets a reference.

Indexed properties

Many COM APIs expose “indexed properties” which are essentially properties with parameters. C# will not allow you to declare indexed properties, but to the extent that non-C# APIs expose them, will now allow you to access these using element access syntax. So instead of
o.set_P(i+1, o.get_P(i) * 2);
You can now write the more intuitive
o.P[i+1] = o.P[i] * 2;

Limitations

A few COM interface features still are not surfaced in C#, most notably default properties. As mentioned above these will be respected if you access COM dynamically, but statically typed C# code will still not recognize them.

Larger COM Example

Here is a larger Office automation example that shows many of the new C# features in action.
using System;
using System.Diagnostics;
using System.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;
class Program
{
    static void Main(string[] args) {
        var excel = new Excel.Application();
        excel.Visible = true;
        excel.Workbooks.Add();                    // optional arguments omitted
        excel.Cells[1, 1].Value = "Process Name"; // no casts; Value dynamically 
        excel.Cells[1, 2].Value = "Memory Usage"; // accessed
        var processes = Process.GetProcesses()
            .OrderByDescending(p =&gt; p.WorkingSet)
            .Take(10);
        int i = 2;
        foreach (var p in processes) {
            excel.Cells[i, 1].Value = p.ProcessName; // no casts
            excel.Cells[i, 2].Value = p.WorkingSet;  // no casts
            i++;
        }
        Excel.Range range = excel.Cells[1, 1];       // no casts
        Excel.Chart chart = excel.ActiveWorkbook.Charts.
            Add(After: excel.ActiveSheet);         // named and optional arguments
        chart.ChartWizard(
            Source: range.CurrentRegion,
            Title: "Memory Usage in " + Environment.MachineName); //named+optional
        chart.ChartStyle = 45;
        chart.CopyPicture(Excel.XlPictureAppearance.xlScreen,
            Excel.XlCopyPictureFormat.xlBitmap,
            Excel.XlPictureAppearance.xlScreen);
        var word = new Word.Application();
        word.Visible = true;
        word.Documents.Add();          // optional arguments
        word.Selection.Paste();
    }
}
The code is much more terse and readable than the C# 3.0 counterpart.

Variance

An aspect of generics that often comes across as surprising is that the following is illegal:
IList<string> strings = new List<string>();
IList<object> objects = strings;
The second assignment is disallowed because strings does not have the same element type as objects. There is a perfectly good reason for this. If it were allowed you could write:
objects[0] = 5;
string s = strings[0];
Allowing an int to be inserted into a list of strings and subsequently extracted as a string. This would be a breach of type safety.
However, there are certain interfaces where the above cannot occur, notably where there is no way to insert an object into the collection. Such an interface is IEnumerable<T>. If instead you say:
IEnumerable<object> objects = strings;
Things are a lot safer: There is no way we can put the wrong kind of thing into strings through objects, because objects doesn’t have a method that takes an element as input. Variance is about allowing assignments such as this in cases where it is safe. The result is that a lot of situations that were previously surprising now just work.

Covariance

In .NET 4.0 the IEnumerable<T> interface will be declared in the following way:
public interface IEnumerable<out T> : IEnumerable
{
           IEnumerator<T> GetEnumerator();
}
public interface IEnumerator<out T> : IEnumerator
{
           bool MoveNext();
           T Current { get; }
}
The “out” in these declarations is a new C# 4.0 modifier which signifies that the T can only occur in output position in the interface – the compiler will complain otherwise. In return for this restriction, the interface becomes “covariant” in T, which means that an IEnumerable<A> is considered an IEnumerable<B> if A has a reference conversion to B.
As a result, any sequence of strings is also e.g. a sequence of objects.
This is useful e.g. in many LINQ methods. Using the declarations above:
var result = strings.Union(objects); // succeeds with an IEnumerable<object>
This would previously have been disallowed, and you would have had to to some cumbersome wrapping to get the two sequences to have the same element type.

Contravariance

Type parameters can also have an “in” modifier, restricting them to occur only in input positions. An example is IComparer<T>:
public interface IComparer<in T>
{
           public int Compare(T left, T right);
}
The somewhat baffling result is that an IComparer<object> can in fact be considered an IComparer<string>! It makes sense when you think about it: If a comparer can compare any two objects, it can certainly also compare two strings. So a comparer of objects is a comparer of strings. This property is referred to as contravariance.
A generic type can have both in and out modifiers on its type parameters, as is the case with the Func<…> delegate types:
public delegate TResult Func<in TArg, out TResult>(TArg arg);
Obviously the argument only ever comes in, and the result only ever comes out. Therefore a Func<object,string> can in fact be used as a Func<string,object>.

Limitations

Variant type parameters can only be declared on interfaces and delegate types, due to a restriction in the CLR. Variance only applies when there is a reference conversion between the type arguments. For instance, an IEnumerable<int> is not an IEnumerable<object> because the conversion from int to object is a boxing conversion, not a reference conversion.

Relationship with Visual Basic

A number of the features introduced to C# 4.0 already exist or will be introduced in some form or other in Visual Basic:
·         Late binding in VB is similar in many ways to dynamic binding in C#. In VB 10 (the “sister” VB version to C# 4.0), late binding has been extended to target the DLR for dynamic objects. Thus VB has the same degree of integration with dynamic objects as does C#.
·         Named and optional arguments have been part of Visual Basic for a long time, and the C# version of the feature is explicitly engineered with maximal VB interoperability in mind.
·         VB also already allows reference parameters to be omitted, and exposes indexed properties.
·         PIA embedding and variance are both being introduced to VB and C# at the same time.
VB in turn is adding a number of features that have hitherto been a mainstay of C#. As a result future versions of C# and VB will have much better feature parity, for the benefit of everyone.