Dec 12, 2012

C# 4.0, Asp.net 4.0 and .Net 4.0 : feature set

C# 4.0 was a deliberately small release as far as new language features go. Feedback we get all the time is "please stop adding crazy new features; spend some time making what you've got work well with everything else you're putting out!" So that's what we did. All the new C# 4.0 features focus on making dynamic languages, static languages and legacy object models/interfaces work together more smoothly. Making interoperability smoother is not exciting so it is unsurprising that you're not excited about it. Our aim is to produce useful tools, and useful is not always thrilling. – Eric Lippert

 -------------------------------------------------------------------

 ASP.Net 4.0

 Here is a very useful whitepaper which covers what’s new in ASP.NET 4.0 and Visual Studio 2010 for Web Development.

http://www.asp.net/whitepapers/aspnet4


------------------------------------------------------------

 What's New in C# and .NET 4

 (http://visualstudiomagazine.com/articles/2010/06/22/whats-new-in-c-and-net-4.aspx)
 
Named and Optional Arguments
With support for named arguments, you can reduce the amount of typing you need to do when calling a method (or indexer, constructor or delegate).

Let's say you have a method with 4 arguments (x, y, width and height). And because this API was designed nicely, the arguments are actually named "x", "y", "width" and "height". When it comes time to calling that method, if you can only remember the argument names but not their position, named arguments will help:
CalulateIntersection(x: 20, y: 30, height: 10, width: 4);
Or maybe it was width and height that went first?
CalulateIntersection(height: 10, width: 4, x: 20, y: 30);
With named arguments, both of these calls are equivalent and pass the same data to the method.
Optional arguments allow you to specify a default value for an argument. The default value will be used if the caller does not provide a value for the optional parameter. The syntax is simple:
public void MakeBeta(int value, string name = "Beta1", string version = "1.0")
In the method signature above, name and version are optional. If not supplied by the caller, "name" will get the value "Beta1" and "version" will be "1.0". Even though optional parameters are, um, optional, you can't leave them out altogether. If you wanted to call "MakeBeta" with the default name but a specific version, you can use named arguments:
MakeBeta(34, version: "2.4");
If you've done any COM-interop, especially with the Microsoft Office COM API's, you'll quickly see how powerful optional and named arguments will be to you. Before named arguments, you had to use Type.Missing for optional parameters:
excelApp.get_Range("A5", "C7").AutoFormat(myFormat, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing);
Now you can take advantage of named arguments and simply supply the format argument:
excelApp.get_Range("A5", "C7").AutoFormat(format:myFormat); 
Good bye Type.Missing! You won't be missed (pardon the pun)!

Dynamic keyword
The "dynamic" keyword allows you to define a type that has its type checking done at runtime rather than compile time. Why would you want to wait until runtime to do your type checking? It allows your application to be more flexible: You don't care where an object came from – COM interop, reflection, a dynamic language like IronPython – you just want to manipulate it.
Consider this example:
public void DoSomething(dynamic x)
 {
  x.ShowSample();
 }
Since "x" is defined as dynamic, no compile-time checks are done. At runtime, the code will work only if the object passed in supports a "ShowSample" method that takes no arguments. It doesn't matter what the type is – as long as it has a "ShowSample" method.
Why defer type checking to runtime? The biggest reason is COM-interop. If you look at some of the Microsoft Office Automation API interfaces, there are a lot of variables and return types defined as "object". This is because the API's were originally designed for a non-type-safe language: VBScript.
With .NET's adherence to strong typing, interop with COM API's like the Microsoft Office API's requires a lot of casting to various interfaces and classes in both method calls as well as return types. It made the code tedious to write and difficult to read.
With the dynamic keyword, we can let the runtime do the type checking and casting for us. A call to set or get the value of a range used to look something like this:
 ((Microsoft.Office.Interop.Excel.Range)excelApp.Cells[5, 5]).Value = "Language";
 var languageRange = (Microsoft.Office.Interop.Excel.Range)excelApp.Cells[5, 5];
Now, by defining the "excelApp" variable as "dynamic", we can let the runtime do the type checking and there is no longer a need to satisfy the compiler with casting:
 excelApp.Cells[5, 5].Value = "Language";
 var languageRange = excelApp.Cells[5, 5];

Type Equivalence Support
Type Equivalence Support (or "Type Embedding") allows you to avoid a major pitfall of writing clients against strongly-type interop assemblies; that is, when a new version of the strongly-typed interop assembly is released, you have to recompile your client – even if you're not using any of the new features.
With type embedding, you can actually embed type information into a client. So if the type information changes on the target machine (because the user upgraded to the next version of Microsoft Office, for example), the type information embedded into the client can be used without the need to recompile the client application.
A simple example of how this works is beyond the scope of this article. See the MSDN documentation on "Walkthrough: Embedding Types from Managed Assemblies" for a complete explanation and sample code.

Covariance and Contravariance
This is one of those tricky things that could take up an entire article. As a matter of fact, former "C# Corner" author Bill Wagner did just that back in May of 2009. His article, "Generic Covariance and Contravariance in C# 4.0" provides an in-depth look at how C# handles type conversions and decides which ones are allowed and which aren't. You can read the article online here.

Covariance and contravariance are best introduced with an example, and the best is in the framework. In System.Collections.Generic, IEnumerable and IEnumerator represent, respectively, an object that’s a sequence of T’s and the enumerator (or iterator) that does the work of iterating the sequence. These interfaces have done a lot of heavy lifting for a long time, because they support the implementation of the foreach loop construct. In C# 3.0, they became even more prominent because of their central role in LINQ and LINQ to Objects—they’re the .NET interfaces to represent sequences.
So if you have a class hierarchy with, say, an Employee type and a Manager type that derives from it (managers are employees, after all), then what would you expect the following code to do?

IEnumerable ms = GetManagers();

IEnumerable es = ms;

It seems as though one ought to be able to treat a sequence of Managers as though it were a sequence of Employees. But in C# 3.0, the assignment will fail; the compiler will tell you there’s no conversion. After all, it has no idea what the semantics of IEnumerable are. This could be any interface, so for any arbitrary interface IFoo, why would an IFoo be more or less substitutable for an IFoo?
In C# 4.0, though, the assignment works because IEnumerable, along with a few other interfaces, has changed, an alteration enabled by new support in C# for covariance of type parameters.
IEnumerable is eligible to be more special than the arbitrary IFoo because, though it’s not obvious at first glance, members that use the type parameter T (GetEnumerator in IEnumerable and the Current property in IEnumerator) actually use T only in the position of a return value. So you only get a Manager out of the sequence, and you never put one in.
In contrast, think of List. Making a List substitutable for a List would be a disaster, because of the following:

List ms = GetManagers();

List es = ms; // Suppose this were possible

es.Add(new EmployeeWhoIsNotAManager()); // Uh oh

As this shows, once you think you’re looking at a List, you can insert any employee. But the list in question is actually a List, so inserting a non-Manager must fail. You’ve lost type safety if you allow this. List cannot be covariant in T.
The new language feature in C# 4.0, then, is the ability to define types, such as the new IEnumerable, that admit conversions among themselves when the type parameters in question bear some relationship to one another. This is what the .NET Framework developers who wrote IEnumerable used, and this is what their code looks like (simplified, of course):

public interface IEnumerable { /* ... */ }

Notice the out keyword modifying the definition of the type parameter, T. When the compiler sees this, it will mark T as covariant and check that, in the definition of the interface, all uses of T are up to snuff (in other words, that they’re used in out positions only—that’s why this keyword was picked).
Why is this called covariance? Well, it’s easiest to see when you start to draw arrows. To be concrete, let’s use the Manager and Employee types. Because there’s an inheritance relationship between these classes, there’s an implicit reference conversion from Manager to Employee:
Manager → Employee
And now, because of the annotation of T in IEnumerable, there’s also an implicit reference conversion from IEnumerable to IEnumerable. That’s what the annotation provides for:
IEnumerable → IEnumerable
This is called covariance, because the arrows in each of the two examples point in the same direction. We started with two types, Manager and Employee. We made new types out of them, IEnumerable and IEnumerable. The new types convert the same way as the old ones.
Contravariance is when this happens backward. You might anticipate that this could happen when the type parameter, T, is used only as input, and you’d be right. For example, the System namespace contains an interface called IComparable, which has a single method called CompareTo:

public interface IComparable { 

  bool CompareTo(T other); 

}

If you have an IComparable, you should be able to treat it as though it were an IComparable, because the only thing you can do is put Employees in to the interface. Because a manager is an employee, putting a manager in should work, and it does. The in keyword modifies T in this case, and this scenario functions correctly:

IComparable ec = GetEmployeeComparer();

IComparable mc = ec;

This is called contravariance because the arrow got reversed this time:
Manager → Employee
IComparable ← IComparable

So the language feature here is pretty simple to summarize: You can add the keyword in or out whenever you define a type parameter, and doing so gives you free extra conversions. There are some limitations, though.
First, this works with generic interfaces and delegates only. You can’t declare a generic type parameter on a class or struct in this manner. An easy way to rationalize this is that delegates are very much like interfaces that have just one method, and in any case, classes would often be ineligible for this treatment because of fields. You can think of any field on the generic class as being both an input and an output, depending on whether you write to it or read from it. If those fields involve type parameters, the parameters can be neither covariant nor contravariant.
Second, whenever you have an interface or delegate with a covariant or contravariant type parameter, you’re granted new conversions on that type only when the type arguments, in the usage of the interface (not its definition), are reference types. For instance, because int is a value type, the IEnumerator doesn’t convert to IEnumerator , even though it looks like it should:
IEnumerator  image: right arrow with slash  IEnumerator
The reason for this behavior is that the conversion must preserve the type representation. If the int-to-object conversion were allowed, calling the Current property on the result would be impossible, because the value type int has a different representation on the stack than an object reference does. All reference types have the same representation on the stack, however, so only type arguments that are reference types yield these extra conversions.
Very likely, most C# developers will happily use this new language feature—they’ll get more conversions of framework types and fewer compiler errors when using some types from the .NET Framework (IEnumerable, IComparable, Func, Action, among others). And, in fact, anyone designing a library with generic interfaces and delegates is free to use the new in and out type parameters when appropriate to make life easier for their users.
By the way, this feature does require support from the runtime—but the support has always been there. It lay dormant for several releases, however, because no language made use of it. Also, previous versions of C# allowed some limited conversions that were contravariant. Specifically, they let you make delegates out of methods that had compatible return types. In addition, array types have always been covariant. These existing features are distinct from the new ones in C# 4.0, which actually let you define your own types that are covariant and contravariant in some of their type parameters.


C# IDE
The C# language wasn't the only part of C# that was improved. Microsoft spent a lot of time on Visual Studio as well. The IDE shell was rewritten in WPF (ever heard of the term "eating your own dog food?") and uses MEF (Managed Extensibility Framework) to offer even more extensibility points. Here are a few C# IDE enhancements in 2010.

Call Hierarchy
This is one of my favorite features in the new IDE. Simply right-click on the name of any method, constructor or property and select "View Call Hierarchy". The Call Hierarchy window will appear. A sample is shown below in Figure 1 for a method called "WhiteOutRows":


[Click on image for larger view.]
Figure 1. Call Hierarchy Window
There are two nodes underneath the method name: Calls To and Calls From. Expanding "Calls To" will show all calls made to the selected item. Likewise, selecting "Calls From" will list all calls made from the method. See Figure 2 where I opened the "Calls From WhiteOutRows" node:

[Click on image for larger view.]
Figure 2. Calls from WhiteOutRows
You can continue to navigate further down the "call stack" since each method and property name listed under the "Calls To" or "Calls From" will have their own "Calls To" and "Calls From" nodes.
This is like a super-charged call stack window – and it's available at design time!

Generate From Usage
As a fan of test-first development, I like the new "Generate From Usage" feature.
Let's say we’re writing a simple banking application and we need to write some code to transfer some money between two accounts. Let’s start with a unit test:
 [TestMethod]
 public void TransferFundsTest()
 {
  Account source = new Account() {Balance = 300.0};
  Account destination = new Account() {Balance = 100.0};
  var xferService = new XferService();

  xferService.Transfer(source, destination, 50.0);

  Assert.AreEqual(250, source.Balance);
  Assert.AreEqual(150, destination.Balance);
 }
Lots of errors in there! That’s because we haven’t even written an Account class or an XferService class. Visual Studio can help us start generating some code based on our unit test.
Right-click on the one of the red "Account" instances and select "Generate" and then "Class". Visual Studio generates a simple Account class with no members. Now right-click on one of the red "Balance" references and select "Generate" and then "Property". Our Account class now has a simple get/set Balance field. Repeat these same steps with XferService and the Transfer method. Without too much work, we’ve got the following code generated from our unit tests:
 class Account
 {
  public double Balance { get; set; }
 }

 class XferService
 {
  internal void Transfer(Account source, Account destination, double p)
  {
   throw new NotImplementedException();
  }
} Not runnable code, but a nice start at fleshing out our design based on our unit tests!

Reference Highlighting
Reference Highlighting adds a nice navigational feature to the IDE. Select any word in the IDE. You’ll notice that all instances of that word are highlighted in the code editor. It’s a quick way to show you where usages of that word object (class, variable, method, property) can be found. And you can navigate between all highlighted instances with CTRL+SHIFT+DOWN ARROW and CTRL+SHIFT+UP ARROW.

Other changes
  1. Better Garbage Collection
  2. New Thread Pooling Engine
  3. Code Contracts
 Learning Resources for .NET 4.0 New Features

Learning resources for C# 4.0 and .NET 4.0 new features

Update 05.08.2009: I have posted learning resources for Entity Framework 4.0 and ASP.NET 4.0 Web Forms. I have also updated the resources for C# 4.0.
Update 13.07.2009: There is a separate post for security transparency.
With the eminent release of a beta release for Visual Studio 2010 next month, I thought it would be nice to have learning resources for the new features introduced in .NET 4.0 and especially in C# 4.0.

New features

http://community.bartdesmet.net/blogs/bart/archive/2009/02/21/net-4-0-system-shell-commandline-parsing-part-1.aspx
http://www.danielmoth.com/Blog/2009/05/vs2010-fix-for-not-all-anonymous.html
http://blogs.msdn.com/bclteam/archive/2009/05/22/what-s-new-in-the-bcl-in-net-4-beta-1-justin-van-patten.aspx
http://community.bartdesmet.net/blogs/bart/archive/2009/07/11/bart-s-control-library-not-what-you-think-it-is-part-0.aspx
http://blogs.msdn.com/charlie/archive/2009/06/11/community-convergence-l.aspx

Dynamic keyword

http://www.codethinked.com/post/2008/10/28/C-40-New-Features-Part-1-dynamic-keyword.aspx
http://www.nikhilk.net/Entry.aspx?id=210
http://www.nikhilk.net/Entry.aspx?id=211
http://www.nikhilk.net/Entry.aspx?id=213
http://geekswithblogs.net/sdorman/archive/2008/11/16/c-4.0-dynamic-programming.aspx
http://blogs.msdn.com/samng/archive/2008/10/29/dynamic-in-c.aspx
http://blogs.msdn.com/samng/archive/2008/11/02/dynamic-in-c-ii-basics.aspx
http://blogs.msdn.com/samng/archive/2008/11/06/dynamic-in-c-iii-a-slight-twist.aspx
http://blogs.msdn.com/samng/archive/2008/11/09/dynamic-in-c-iv-the-phantom-method.aspx
http://blogs.msdn.com/samng/archive/2008/12/11/dynamic-in-c-v-indexers-operators-and-more.aspx
http://blogs.msdn.com/samng/archive/2008/12/15/dynamic-in-c-vi-what-dynamic-does-not-do.aspx
http://blogs.msdn.com/samng/archive/2008/12/24/dynamic-in-c-vii-phantom-method-semantics.aspx
http://blogs.msdn.com/kirillosenkov/archive/2009/05/01/a-simple-sample-for-c-4-0-dynamic-feature.aspx
http://www.hanselman.com/blog/C4AndTheDynamicKeywordWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx
http://blogs.msdn.com/cburrows/archive/2008/10/27/c-dynamic.aspx
http://blogs.msdn.com/cburrows/archive/2008/10/28/c-dynamic-part-ii.aspx
http://blogs.msdn.com/cburrows/archive/2008/10/29/c-dynamic-part-iii.aspx
http://blogs.msdn.com/cburrows/archive/2008/11/06/c-dynamic-part-iv.aspx
http://blogs.msdn.com/cburrows/archive/2008/11/11/c-dynamic-part-v.aspx
http://blogs.msdn.com/cburrows/archive/2008/11/14/c-dynamic-part-vi.aspx
http://blogs.msdn.com/cburrows/archive/2009/02/04/c-dynamic-part-vii.aspx
http://blogs.msdn.com/cburrows/archive/2009/04/22/dynamic-base-classes-in-c-4.aspx
http://blogs.msdn.com/ericlippert/archive/2009/07/30/generics-are-not-templates.aspx

COM Interop

http://www.hanselman.com/blog/CLRAndDLRAndBCLOhMyWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx
http://channel9.msdn.com/shows/Going+Deep/Raja-Krishnaswamy-and-Vance-Morrison-CLR-4-Inside-Type-Equivalence/
http://blogs.msdn.com/samng/archive/2009/06/16/com-interop-in-c-4-0.aspx
http://blogs.msdn.com/clrteam/archive/2009/08/10/improvements-to-interop-marshaling-in-v4-il-stubs-everywhere.aspx

Covariance and contravariance

http://blogs.msdn.com/charlie/archive/2008/10/28/linq-farm-covariance-and-contravariance-in-visual-studio-2010.aspx
http://www.codethinked.com/post/2008/10/31/C-40-New-Features-Part-3-Generic-Covariance.aspx
http://www.codethinked.com/post/2008/11/11/C-40-New-Features-Part-4-Generic-Contravariance.aspx
http://community.bartdesmet.net/blogs/bart/archive/2009/04/13/c-4-0-feature-focus-part-4-generic-co-and-contra-variance-for-delegate-and-interface-types.aspx
http://blogs.msdn.com/wriju/archive/2009/07/31/c-4-0-co-variance-and-contra-variance.aspx

Named and optional parameters

http://blogs.msdn.com/tomholl/archive/2008/11/18/constructors-and-inheritance-why-is-this-still-so-painful.aspx
http://www.codethinked.com/post/2008/10/30/C-40-New-Features-Part-21-default-parameter-intrigue.aspx
http://www.codethinked.com/post/2008/10/29/C-40-New-Features-Part-2-default-and-named-parameters.aspx
http://blogs.msdn.com/samng/archive/2009/02/03/named-arguments-optional-arguments-and-default-values.aspx
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2009/03/27/c-and-optional-parameters.aspx
http://blogs.msdn.com/samng/archive/2009/04/01/named-arguments-and-overload-resolution.aspx
http://blogs.msdn.com/samng/archive/2009/04/17/named-and-optional-arguments-ties-and-philosophies.aspx
http://davidhayden.com/blog/dave/archive/2009/06/02/CSharp4OptionalNamedParameters.aspx

CLR

http://blogs.msdn.com/clrteam/archive/2009/07/15/clr-4-making-the-assemblyresolve-event-more-useful.aspx
http://channel9.msdn.com/shows/Going+Deep/Raja-Krishnaswamy-and-Vance-Morrison-CLR-4-Inside-Type-Equivalence/
http://blogs.msdn.com/clrteam/archive/2009/06/19/tail-call-improvements-in-net-framework-4.aspx
http://blogs.msdn.com/clrteam/archive/2009/07/15/clr-4-making-the-assemblyresolve-event-more-useful.aspx

Thread pool engine

http://www.danielmoth.com/Blog/2008/11/new-and-improved-clr-4-thread-pool.html
http://www.danielmoth.com/Blog/2008/12/introducing-new-task-type.html
http://blogs.msdn.com/ericeil/archive/2009/04/23/clr-4-0-threadpool-improvements-part-1.aspx
http://channel9.msdn.com/shows/Going+Deep/Erika-Parsons-and-Eric-Eilebrecht–CLR-4-Inside-the-new-Threadpool/
http://channel9.msdn.com/shows/Going+Deep/CLR-4-Side-by-Side-In-Process-What-How-Why/

Garbage collector

http://geekswithblogs.net/sdorman/archive/2008/11/07/clr-4.0-garbage-collection-changes.aspx
http://blogs.msdn.com/tess/archive/2009/05/29/background-garbage-collection-in-clr-4-0.aspx

Code contracts

http://geekswithblogs.net/sdorman/archive/2008/11/07/clr-4.0-code-contracts.aspx
http://geekswithblogs.net/sdorman/archive/2008/12/10/more-on-.net-4.0-code-contracts.aspx
http://odetocode.com/Blogs/scott/archive/2009/02/24/12574.aspx
http://blogs.msdn.com/bclteam/archive/2009/02/23/preview-of-code-contract-tools-now-available-melitta-andersen.aspx
http://devlicio.us/blogs/derik_whittaker/archive/2009/06/08/code-contracts-primer-part-1-introduction.aspx
http://devlicio.us/blogs/derik_whittaker/archive/2009/06/09/code-contracts-primer-part-2-handling-legacy-code.aspx
http://devlicio.us/blogs/derik_whittaker/archive/2009/06/13/code-contracts-primer-part-3-providing-support-for-unit-tests.aspx
http://devlicio.us/blogs/derik_whittaker/archive/2009/06/15/code-contracts-primer-part-4-utilizing-pre-amp-post-conditions.aspx
http://dddstepbystep.com/blogs/ontheweb/archive/2009/07/01/code-contracts-primer-part-5-utilizing-object-invariants-by-derik-whittaker.aspx
http://msdn.microsoft.com/en-us/magazine/ee236408.aspx

Corrupting State Exceptions

http://geekswithblogs.net/sdorman/archive/2008/11/07/clr-4.0-corrupting-state-exceptions.aspx

Managed languages

http://geekswithblogs.net/sdorman/archive/2008/11/10/clr-4.0-managed-languages.aspx

Parallel Programming

http://www.danielmoth.com/Blog/2009/01/parallelising-loops-in-net-4.html
http://managed-world.com/archive/2009/02/09/an-intro-to-barrier.aspx
http://blogs.msdn.com/pfxteam/archive/2009/03/27/9514938.aspx
http://www.danielmoth.com/Blog/2009/05/tasks-documentation.html
http://www.danielmoth.com/Blog/2009/05/parallel-tasks-new-visual-studio-2010.html
http://www.danielmoth.com/Blog/2009/05/parallel-tasks-new-visual-studio-2010.html
http://www.danielmoth.com/Blog/2009/05/tasks-documentation.html
http://www.danielmoth.com/Blog/2009/05/vs2010-fix-for-not-all-anonymous.html
http://www.danielmoth.com/Blog/2009/06/parallel-stacks-method-view.html
http://www.codethinked.com/post/2009/06/15/Life-After-Loops.aspx
http://geekswithblogs.net/jolson/archive/2009/06/09/parallel-computing-with-visual-studio-2010-beta-1.aspx
http://www.bluebytesoftware.com/blog/PermaLink,guid,652962f1-5073-49a4-b233-9ca24b494742.aspx

System.Core

http://community.bartdesmet.net/blogs/bart/archive/2009/02/21/net-4-0-system-shell-commandline-parsing-part-1.aspx

Security

http://blogs.msdn.com/shawnfa/archive/2009/05/20/net-4-0-security.aspx
http://blogs.msdn.com/shawnfa/archive/2009/05/21/security-policy-in-the-v4-clr.aspx
http://blogs.msdn.com/shawnfa/archive/2009/05/22/sandboxing-in-net-4-0.aspx
http://blogs.msdn.com/shawnfa/archive/2009/05/27/coding-with-security-policy-in-net-4-0-implicit-uses-of-cas-policy.aspx
http://blogs.msdn.com/krimakey/archive/2009/05/20/where-did-my-permission-set-controls-go.aspx
There is a separate post for security transparency.

LINQ

http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40
http://community.bartdesmet.net/blogs/bart/archive/2009/08/10/expression-trees-take-two-introducing-system-linq-expressions-v4-0.aspx

Tuple

http://blogs.msdn.com/bclteam/archive/2009/07/07/building-tuple-matt-ellis.aspx
http://msdn.microsoft.com/en-us/magazine/dd942829.aspx

Registry

http://www.danielmoth.com/Blog/2009/07/registryoptionsvolatile-in-net-4.html