29
up vote46down voteaccepted What is new in .NET Framework 4.5 & What's new and expected in .NET Framework 4.5 Support for Windows Runtime Support for Metro Style Applications Support for Async Programming Garbage Collector Improvements Faster ASP.NET Startup Better Data Access Support WebSockets Support Workflow Support - BCL Support differences in ASP.NET in these frameworks Compare What's New in ASP.NET 4 and Visual Web Developer and What's New in ASP.NET 4.5 and Visual Studio 11 Beta -Asp.net 4.0 Web.config File Refactoring Extensible Output Caching Auto-Start Web Applications Permanently Redirecting a Page Shrinking Session State Expanding the Range of Allowable URLs Extensible Request Validation Object Caching and Object Caching Extensibility Extensible HTML, URL, and HTTP Header Encoding Performance Monitoring for Individual Applications in a Single Worker Process Multi-Targeting .... etc And Asp.net 4.5 there is also a long list of improvements. Asynchronously Reading and Writing HTTP Requests and Responses Improvements to HttpRequest handling Asynchronously flushing a response Support for await and Task-Based Asynchronous Modules and Handlers differences in C# also in these frameworks Go Through C# 4.0 - New C# Features in the .NET

dotnet 4 and 4.5.docx

  • Upload
    deepa

  • View
    231

  • Download
    3

Embed Size (px)

Citation preview

up vote46down voteacceptedWhat is new in .NET Framework 4.5&What's new and expected in .NET Framework 4.5Support for Windows RuntimeSupport for Metro Style ApplicationsSupport for Async ProgrammingGarbage Collector ImprovementsFaster ASP.NET StartupBetter Data Access SupportWebSockets SupportWorkflow Support - BCL Supportdifferences in ASP.NET in these frameworksCompareWhat's New in ASP.NET 4 and Visual Web DeveloperandWhat's New in ASP.NET 4.5 and Visual Studio 11 Beta-Asp.net 4.0Web.config File RefactoringExtensible Output CachingAuto-Start Web ApplicationsPermanently Redirecting a PageShrinking Session StateExpanding the Range of Allowable URLsExtensible Request ValidationObject Caching and Object Caching ExtensibilityExtensible HTML, URL, and HTTP Header EncodingPerformance Monitoring for Individual Applications in a Single Worker ProcessMulti-Targeting.... etcAnd Asp.net 4.5 there is also a long list of improvements.Asynchronously Reading and Writing HTTP Requests and ResponsesImprovements to HttpRequest handlingAsynchronously flushing a responseSupport for await and Task-Based Asynchronous Modules and Handlersdifferences in C# also in these frameworks Go ThroughC# 4.0 - New C# Features in the .NET FrameworkandWhat's New for Visual C# in Visual Studio 11 BetaEdit:The languages documentation for C# and VB breaking changes:VB:Visual Basic Breaking Changes in Visual Studio 2012C#:Visual C# Breaking Changes in Visual Studio 2012Hope this help you get what are you looking for..

4.5 five great features:http://www.codeproject.com/Articles/599756/Five-Great-NET-Framework-FeaturesFive Great .NET Framework 4.5 Features

Shivprasad koirala,6 Feb 2014CPOL

4.91(321votes)

Rate this:vote 1vote 2vote 3vote 4vote 5

In this article I have picked my five favorite features introduced in the .NET 4.5 core framework.Table of contents Introduction Feature 1: async and await (code markers) Feature 2: Zip facility (Zip compression) Feature 3: Regex timeout (TimeOut) Feature 4: Profile optimization (Improved startup performance) Feature 5: Garbage collector (GC background cleanup) Three more features worth exploring ReferencesIntroductionIt has been almost a year since .NET 4.5 got released. But the problems with most of the recent Microsoft releases have been communication with .NET developers. Only one or two features are known to developers and other features just stay on MSDN and end up becoming simple documents.For example, the time you ask a .NET developer what is new in the core framework .NET 4.5 most of them will just sayasyncandawaitt(at least with people whom I have interacted have just talked about those features).Again its very difficult to run through all the new features. Because the features may not sound interesting depending on what you are working currently on..So in this article I have picked my five favorite features introduced in .NET 4.5 core. Again its possible my favorites cannot be your favorites. But what I have done is while choosing these features I kept in mind the larger .NET community and I hope I have met that expectation.

Note:This article does not discuss the new features in ASP.NET, WCF, WPF, WWF etc. It only talks about new features related to the core.Feature 1: async and await (code markers)This feature has been oversold and every .NET evangelist has talked about it. But this is still my favorite and you will come to know why in a few lines from here.

asyncandawaitare markers which mark code positions from where control should resume after a task (thread) completes.Let us try to make sense of the above statement by understanding the below code. If you see the flow of the below code:1. Method()gets called from theStatic void main()entry point.2. Method()spawns aTask(thread)LongTaskwhich waits for 10 seconds.3. At the same time the control comes back toMethod()to execute the remaining code after the task was called. In other words as the invocation is multi-threaded (Task.Run), LongTaskis also running i.e., waiting for 10 seconds and the remaining code of yourMethod()is also executed.Now in certain scenarios we want step 3 to behave differently. We want that afterLongTask()finishes execution, the control should go back toMethodto execute the remaining code. Theasyncandawaitkeywords help to achieve the above behavior.

Now there are three important points to remember about theasyncandawaitkeywords:1. asyncandawaitare pair keywords. You cannot use them in a standalone manner.2. asyncis marked on a method. This keyword is just an indicator saying that this method will have theawaitkeyword.3. Theawaitkeyword marks the position from where the task should resume. So you will always find this keyword in conjunction withTask.Below is a modified version of the previously discussed code where we have appliedasyncandawait. All the other steps remain the same but Step 3 is executed after Step 2 completes. In simple words the control comes back toMethod()after the task has finished operation.

Now that you have read about async and await, let me put a cross question. The above behavior can be also achieved by usingTask.WaitorTask.ContinueWith, so how do they differ? I am leaving this question as a home work for you.Feature 2: Zip facility (Zip compression)

Zip is one of the most accepted archive file formats. Zip format is supported in almost all operating systems with some built-in name. In Windows operating system its implemented by the name Compressed folders. In MAC OS its implemented by the name Archive utility.Now in .NET we did not have built-in support for implementing Zip compression. Many developers where using third party components like DotnetZip. In .NET 4.5, the Zip feature is baked in the framework itself, inside the namespaceSystem.IO.Compression.The first step is you need to reference two namespaces: System.IO.Compression.FileSystem System.IO.CompressionThe next step is to import the below two namespaces:HideCopy Codeusing System.IO.Compression;If you want to Zip files from a folder you can use theCreateFromDirectoryfunction as shown below.HideCopy CodeZipFile.CreateFromDirectory(@"D:\data",@"D:\data.zip");If you wish to unzip, you can use theExtractToDirectoryfunction as shown in the below code.HideCopy CodeZipFile.ExtractToDirectory(@"D:\data.zip", @"D:\data\unzip");Feature 3: Regex timeout (TimeOut)

Regex has been the most preferred way of doing validations. In case you are new to Regex, pleasesee the Regex videowhere I have explained how regex is implemented. But because of the typical parsing logic of regex it is exposed to DOS attacks. Let us try to understand in detail what I mean by that.For instance consider this regular expression - ^(\d+)$. This regex expression says that it can have only numbers. You can also see the regex symbolic diagram which shows how the regex will be evaluated .Now lets say if we want to validate 123456X. It will have six paths as shown in the below figure.

But if we add one more number to it, it will take seven paths. In other words as the length increases a regex takes more time to evaluate. In other words the time taken to evaluate is linearly proportional to the length of the characters.

Now lets complicate the previously defined regex from ^(\d+)$ to ^(\d+)+$ . If you see the regex symbolic diagram its pretty complex. If we now try to validate 123456X, it will run through 32 paths. If you add one more character the number pf paths become 64.

In other words for the above regex, the time taken to evaluate rises exponentially with the number of characters.

Now the question you would ask is, how does it matter? This linear rise of evaluation time can be exploited by hackers to do a DOS (Denial of Service) attack. They can put a long, a really long string and make your application hang forever.The proper solution for this would be to have a timeout on the regex operation. Good news, in .NET 4.5 you can now define a timeout property as shown in the below code. So if you get any kind of malicious string, the application will not go in a loop forever.HideCopy Codetry{ var regEx = new Regex(@^(\d+)+$, RegexOptions.Singleline, TimeSpan.FromSeconds(2)); var match = regEx.Match(123453109839109283090492309480329489812093809x);}catch (RegexMatchTimeoutException ex){ Console.WriteLine(Regex Timeout);}Below is a nice video which is uploaded on Facebook which demonstrates the DOS attack by regular expression and how it can be prevented using regex timeout feature of .NET 4.5. Do not miss it, worth a watch.Feature 4: Profile optimization (Improved startup performance)

We all know .NET code is in a half compiled format. During runtime, the JIT (Just-in-Time) compiler runs and translates this half compiled IL code to native machine code. One of the big complaints about JIT is that when a .NET applications runs the first time, it runs slow as JIT is busy translating IL code to machine code.In order to bring down this startup time, in .NET 4.5, we have something called profile optimization. Profile is nothing but a simple file which has a list of methods which the application will need during startup. So when the application starts, a background JIT runs and starts translating IL code for those methods into machine / native code.This background JIT compilation of startup methods happens across multiple processors thus minimizing the start up time further. Also noteyou need to have a multicore box to implement profile optimization. In case you do not have a multicore box then this setting is ignored.

In order to create the profile file, you first need to import theSystem.Runtimenamespace. You can then call theSetProfileRootandStartProfilemethods of the static classProfileOptimization. Now when the application starts the background JIT it will read from the profile file and compile your start up methods in the background thus reducing your startup time.HideCopy Codeusing System.Runtime;

// Call the Setprofilerroot and Startprofile methodProfileOptimization.SetProfileRoot(@"D:\ProfileFile");

ProfileOptimization.StartProfile("ProfileFile");One important note:Profileoptimizationis enabled by default for ASP.NET 4.5 and Silverlight 5 applications. So the above code need not be written for these technologies.Feature 5: Garbage collector (GC background cleanup)

Garbage collector is one real heavy task in a .NET application. And it becomes heavier when it is an ASP.NET application. ASP.NET applications run on the server and a lot of clients send requests to the server thus creating loads of objects, making the GC really work hard for cleaning up unwanted objects.

In .NET 4.0, when the GC runs for cleanup, all the application threads are suspended. You can see in the above figure we have three application threads running. We have two GCs running on separate threads. One GC thread for one logical processor. Now the application threads run and do their work. Now as these application threads are performing their task they also create managed objects.At some point of time the background GC runs and starts clean up. When these background GCs start cleanup, they suspend all the application threads. This makes the server/application less responsive for that moment.

To overcome the above problem, server GC was introduced. In server GC there is one more thread created which runs in the background. This thread works in the background and keeps cleaning generation 2 (see this video for GC generation 0, 1, and 2)objects thus minimizing the load on the main GC thread. Due to double GC threads running, the main application threads are less suspended, thus increasing application throughput. To enable server GC, we need to use thegcServerXML tag and enable it totrue.HideCopy Code

Three more features worth exploringSet default culture to App DomainIn the previous versions of .NET if I needed to set culture I needed to do it in every thread. Below is a sample code which demonstrates the pain of setting culture at thread levels. That was a real pain when we had heavily multi-threaded applications.HideCopy CodeCultureInfo cul = new CultureInfo(strCulture);Thread.CurrentThread.CurrentCulture = cul;Thread.CurrentThread.CurrentUICulture = cul;In 4.5 we can set culture at the app domain level and all the threads inside that appdomain will inherit that culture. Below is a sample code of how to implementDefaultThreadCurrentCulture.HideCopy CodeCultureInfo culture = CultureInfo.CreateSpecificCulture("fr-FR");CultureInfo.DefaultThreadCurrentCulture = culture;Array support more than two gigabyte sizeI am not sure in what kind of a scenario we would need a 2 GB collection. So I personally do not see where we would need this feature. If I ever need such a big collection I would break it into parts. But I am sure there should be a good reason for this feature to be enabled in the framework.Unicode support for consoleI left this feature out from the discussion as very less people work with console applications. I have seen people using consoles for academic purposes. All said and done we now have Unicode support for console apps also.References http://msdn.microsoft.com/en-us/library/ms171868.aspx Awesome Article by Mr Sukesh marla onASP.NET 4.5 new featuresWhen you have free time, do visit my sitewww.questpond.comfor.NET 4.5 interview questions with answer videos, I have put in a lot of effort in developing this.

C# 4.0 new featuresC# 4.0's New Features Explained

Josh Fischer,16 Aug 2009CPOL

4.77(143votes)

Rate this:vote 1vote 2vote 3vote 4vote 5

A guide to C# 4.0's new features - explained with code examples and a little historical perspective.IntroductionThe Beta for Visual Studio 2010 is upon us and included is the CTP of C# 4.0. While C# 4.0 does not represent a radical departure from the previous version, there are some key features that should be understood thoroughly in order to take advantage of their true potential.BackgroundThe white paper for C# 4.0's features does a good job of explaining the changes in the language. I thought, however, that some larger code samples and historical perspective would help people (especially new developers) in understanding why things have changed.Feature CategoriesMicrosoft breaks the new features into the following four categories so I will maintain the pattern: Named and Optional Parameters Dynamic Support Variance COM InteropConventionsSome of the examples assume the following classes are defined:HideCopy Codepublic class Person{ public string FirstName { get; set; } public string LastName { get; set; }}

public class Customer : Person{ public int CustomerId { get; set; } public void Process() { ... }}

public class SalesRep : Person{ public int SalesRepId { get; set; } public void SellStuff() { ... }}Named and Optional ParametersWe'll start off with one of the easier features to explain. In fact, if you have ever used Visual Basic, then you are probably already familiar with it.Optional ParametersSupport for optional parameters allows you to give a method parameter a default value so that you do not have to specify it every time you call the method. This comes in handy when you have overloaded methods that are chained together.The Old WayHideCopy Codepublic void Process( string data ){ Process( data, false );}

public void Process( string data, bool ignoreWS ){ Process( data, ignoreWS, null );}

public void Process( string data, bool ignoreWS, ArrayList moreData ){ // Actual work done here}The reason for overloadingProcessin this way is to avoid always having to include "false, null" in the third method call. Suppose 99% of the time there will not be 'moreData' provided. It seems ridiculous to type and passnullso many times.HideCopy Code// These 3 calls are equivalentProcess( "foo", false, null );Process( "foo", false );Process( "foo" );The New WayHideCopy Codepublic void Process( string data, bool ignoreWS = false, ArrayList moreData = null ){ // Actual work done here}// Note: data must always be provided because it does not have a default valueNow we have one method instead of three, but the three ways we calledProcessabove are still valid and still equivalent.HideCopy CodeArrayList myArrayList = new ArrayList();Process( "foo" ); // validProcess( "foo", true ); // validProcess( "foo", false, myArrayList ); // validProcess( "foo", myArrayList ); // Invalid! See next sectionAwesome, one less thing VB programmers can brag about having to themselves. I haven't mentioned it up to this point, but Microsoft has explicitly declared that VB and C# will be "co-evolving" so the number of disparate features is guaranteed to shrink over time. I would like to think this will render the VB vs. C# question moot, but I'm sure people will still find a way to argue about it.Named ParametersIn the last example, we saw that the following call was invalid:HideCopy CodeProcess( "foo", myArrayList ); // Invalid!But if the booleanignoreWSis optional, why can't we just omit it? Well, one reason is for readability and maintainability, but primarily because it can become impossible to know what parameter you are specifying. If you had two parameters of the same type, or if one of the parameters was "object" or some other base class or interface, the compiler would not know which parameter you are sending. Imagine a method with ten optional parameters and you give it a singleArrayList. Since anArrayListis also anobject, anIList, and anIEnumerable, it is impossible to determine how to use it. Yes, the compiler could just pick the first valid option for each parameter (or a more complex system could be used), but this would become impossible for people to maintain and would cause countless programming mistakes.Named parameters provide the solution:HideCopy CodeArrayList myArrayList = new ArrayList();Process( "foo", true ); // valid, moreData omittedProcess( "foo", true, myArrayList ); // validProcess( "foo", moreData: myArrayList); // valid, ignoreWS omittedProcess( "foo", moreData: myArrayList, ignoreWS: false ); // valid, but sillyAs long as a parameter has a default value, it can be omitted, and you can just supply the parameters you want via their name. Note in the second line above, the 'true' value forignoreWSdid not have to be named since it is the next logical parameter.Dynamic SupportOK, I'm sure we all have had to deal with code similar to the following:HideCopy Codepublic object GetCustomer(){ Customer cust = new Customer(); ... return cust;}...Customer cust = GetCustomer() as Customer;if( cust != null ){ cust.FirstName = "foo";}Note theGetCustomermethod returnsobjectinstead ofCustomer. Code like this is frustrating because you know it returns aCustomer; it always has and it always will. Unfortunately, the coder chose to returnobjectand you can't change it because it modifies the public contract and could potentially break legacy software.Another instance in which you will be dealing with an object that you know is another type is Reflection.HideCopy CodeType myType = typeof( Customer );ConstructorInfo consInfo = myType.GetContructor(new Type[]{});object cust = consInfo.Invoke(new object[]{});((Customer)cust).FirstName = "foo";Because Reflection can act on any type,ConstructorInfo.Invoke()must returnobject. Like the first example, this forces you to cast the object. Now, consider the situation where you can't, or don't want to, cast the object. Perhaps, the code author is always changing the name of the type or creating different versions (e.g., 'Customer2'), but the properties and methods stay the same. The examples above assume you, as the programmer, have knowledge of what the true type is. What if you didn't? What if you had to use Reflection to find and invoke methods? What if the object being returned was coming from IronPython, JavaScript, COM, or some other non-statically typed environment?Enter 'dynamic'Thedynamickeyword is new to C# 4.0, and is used to tell the compiler that a variable's type can change or that it is not known until runtime. Think of it as being able to interact with anObjectwithout having to cast it.HideCopy Codedynamic cust = GetCustomer();cust.FirstName = "foo"; // works as expectedcust.Process(); // works as expectedcust.MissingMethod(); // No method found!Notice we did not need to cast nor declarecustas typeCustomer. Because we declared itdynamic, the runtime takes over and then searches and sets theFirstNameproperty for us. Now, of course, when you are using a dynamic variable, you are giving up compiler type checking. This means the callcust.MissingMethod()will compile and not fail until runtime. The result of this operation is aRuntimeBinderExceptionbecauseMissingMethodis not defined on theCustomerclass.The example above shows howdynamicworks when calling methods and properties. Another powerful (and potentially dangerous) feature is being able to reuse variables for different types of data. I'm sure the Python, Ruby, and Perl programmers out there can think of a million ways to take advantage of this, but I've been using C# so long that it just feels "wrong" to me.HideCopy Codedynamic foo = 123;foo = "bar";OK, so you most likely will not be writing code like the above very often. There may be times, however, when variable reuse can come in handy or clean up a dirty piece of legacy code. One simple case I run into often is constantly having to cast betweendecimalanddouble.HideCopy Codedecimal foo = GetDecimalValue();foo = foo / 2.5; // Does not compilefoo = Math.Sqrt(foo); // Does not compilestring bar = foo.ToString("c");The second line does not compile because 2.5 is typed as adoubleand line 3 does not compile becauseMath.Sqrtexpects adouble. Obviously, all you have to do is cast and/or change your variable type, but there may be situations wheredynamicmakes sense to use.HideCopy Codedynamic foo = GetDecimalValue(); // still returns a decimalfoo = foo / 2.5; // The runtime takes care of this for usfoo = Math.Sqrt(foo); // Again, the DLR works its magicstring bar = foo.ToString("c");UpdateAfter some great questions and feedback, I realized I need to clarify a couple points I made above. When you use thedynamickeyword, you are invoking the new Dynamic Language Runtime libraries (DLR) in the .NET framework. There is plenty of information about the DLR out there, and I am not covering it in this article. Also, when possible, you should always cast your objects and take advantage of type checking. The examples above were meant to show howdynamicworks and how you can create an example to test it. Over time, I'm sure best practices will emerge; I am making no attempt to create recommendations on the use of the DLR ordynamic.Also, since publishing the initial version of this article, I have learned that if the object you declared asdynamicis a plain CLR object, Reflection will be used to locate members and not the DLR. Again, I am not attempting to make a deep dive into this subject, so please check other information sources if this interests you.Switching Between Static and DynamicIt should be apparent that 'switching' an object from being statically typed to dynamic is easy. After all, how hard is it to 'lose' information? Well, it turns out that going from dynamic to static is just as easy.HideCopy CodeCustomer cust = new Customer();dynamic dynCust = cust; // static to dynamic, easy enoughdynCust.FirstName = "foo";Customer newCustRef = dynCust; // Works because dynCust is a CustomerPerson person = dynCust; // works because Customer inherits from PersonSalesRep rep = dynCust; // throws RuntimeBinderException exceptionNote that in the example above, no matter how many different ways we reference it, we only have oneCustomerobject (cust).FunctionsWhen you return something from a dynamic function call, indexer, etc., the result is always dynamic. Note that you can, of course, cast the result to a known type, but the object still starts out dynamic.HideCopy Codedynamic cust = GetCustomer();string first = cust.FirstName; // conversion occursdynamic id = cust.CustomerId; // no conversionobject last = cust.LastName; //conversion occursThere are, of course, a few missing features when it comes to dynamic types. Among them are: Extension methods are not supported Anonymous functions cannot be used as parametersWe will have to wait for the final version to see what other features get added or removed.VarianceOK, a quick quiz. Is the following legal in .NET?HideCopy Code// Example stolen from the whitepaper ;-)IList strings = new List();IList objects = strings;I think most of us, at first, would answer 'yes' because astringis anobject. But the question we should be asking ourselves is: Is a -list- ofstrings a -list- ofobjects? To take it further: Is a -strongly typed- list ofstrings a -strongly typed- list ofobjects? When phrased that way, it's easier to understand why the answer to the question is 'no'. If the above example was legal, that means the following line would compile:HideCopy Codeobjects.Add(123);Oops, we just inserted the integer value123into aList. Remember, the list contents were never copied; we simply have two references to the same list. There is a case, however, when casting the list, this should be allowed. If the list is read-only, then we should be allowed to view the contents any (type legal) way we want.Co and Contra VarianceFrom Wikipedia:Within the type system of a programming language, a type conversion operator is: covariant if it preserves the ordering, =, of types, which orders types from more specific to more generic; contravariant if it reverses this ordering, which orders types from more generic to more specific; invariant if neither of these apply.C# is, of course, covariant, meaning aCustomeris aPersonand can always be referenced as one. There are lots of discussions on this topic, and I will not cover it here. The changes in C# 4.0 only involve typed (generic) interfaces and delegates in situations like in the example above. In order to support co and contra variance, typed interfaces are going to be given 'input' and 'output' sides. So, to make the example above legal,IListmust be declared in the following manner:HideCopy Codepublic interface IList : ICollection, IEnumerable, IEnumerable{ ...}Notice the use of theoutkeyword. This is essentially saying theIListis readonly and it is safe to refer to aListas aList. Now, of course,IListis not going to be defined this way; it must support having items added to it. A better example to consider isIEnumerablewhich should be, and is, readonly.HideCopy Codepublic interface IEnumerable : IEnumerable{ IEnumerator GetEnumerator();}Usingoutto basically mean 'read only' is straightforward, but when does using theinkeyword to make something 'write only' useful? Well, it actually becomes useful in situations where a generic argument is expected and only used internally by the method.ICompareris the canonical example.HideCopy Codepublic interface IComparer{ public int Compare(T left, T right);}As you can see, we can't get back an item of typeT. Even though theComparemethod could potentially act on the left and right arguments, it is kept within the method so it is a 'black hole' to clients that use the interface.To continue the example above, this means that anIComparercan be used in the place of anIComparer. The C# 4.0 whitepaper sums the reason up nicely: 'If a comparer can compare any two objects, it can certainly also compare twostrings'. This is counter-intuitive (or maybe contra-intuitive) because if a method expects astring, you can't give it anobject.Putting it TogetherOK, comparingstrings andobjects is great, but I think a somewhat realistic example might help clarify how the new variance keywords are used. This first example demonstrates the effects of the redefinedIEnumerableinterface in C# 4.0. In .NET 3.5, line 3 below does not compile with an the error: 'can not convert List to List'. As stated above, this seems 'wrong' because aCustomeris aPerson. In .NET 4.0, however, this exact same code compiles without any changes becauseIEnumerableis now defined with theoutmodifier.HideCopy CodeMyInterface customers = new MyClass();List people = new List();people.AddRange(customers.GetAllTs()); // no in 3.5, yes in 4.0people.Add(customers.GetAllTs()[0]); // yes in both...interface MyInterface{ List GetAllTs();}public class MyClass : MyInterface{ public List GetAllTs() { return _data; } private List _data = new List();}This next example demonstrates how you can take advantage of theoutkeyword. In .NET 3.5, line 3 compiles, but line 4 does not with the same 'cannot convert' error. To make this work in .NET 4.0, simply change the declaration ofMyInterfacetointerface MyInterface. Notice that in line 4,TisPerson, but we are passing theCustomerversion of the class and interface.HideCopy CodeMyInterface people = new MyClass();MyInterface customers = new MyClass();FooClass.GetThirdItem(people);FooClass.GetThirdItem(customers);...public class FooClass{ public static T GetThirdItem(MyInterface foo) { return foo.GetItemAt(2); }}public interface MyInterface{ T GetItemAt(int index);}public class MyClass : MyInterface{ public T GetItemAt(int index) { return _data[index]; } private List _data = new List();}This final example demonstrates the wacky logic of contravariance. Notice that we put aSalesRep'inside' ourPersoninterface. This isn't a problem because aSalesRepis aPerson. Where it gets interesting is when we pass theMyInterfacetoFooClass. In essence, we have 'inserted' aSalesRepinto an interface declared to work with onlyCustomers! In .NET 3.5, line 5 does not compile; as expected. By adding theinkeyword to our interface declaration in .NET 4.0, everything works fine because we are 'agreeing' to treat everything as aPersoninternally and not expose the internal data (which might be thatSalesRep).HideCopy CodeMyInterface customer = new MyClass();MyInterface person = new MyClass();person.SetItem(new SalesRep());FooClass.Process(customer);FooClass.Process(person);...public class FooClass{ public static void Process(MyInterface obj) { }}public interface MyInterface{ void SetItem(T obj); void Copy(T obj);}public class MyClass : MyInterface{ public void SetItem(T obj) { _item = obj; } private T _item; public void Copy(T obj) { }}COM InteropThis is by far the area in which I have the least experience; however, I'm sure we have all had to interact with Microsoft Office at one point and make calls like this:HideCopy Code// Code simplified for this exampleusing Microsoft.Office.Interop;using Microsoft.Office.Interop.Word;

object foo = "MyFile.txt";object bar = Missing.Value;object optional = Missing.Value;

Document doc = (Document)Application.GetDocument(ref foo, ref bar, ref optional);doc.CheckSpelling(ref optional, ref optional, ref optional, ref optional);There are (at least) three problems with the code above. First, you have to declare all your variables asobjects and pass them with therefkeyword. Second, you can't omit parameters and must also pass theMissing.Valueeven if you are not using the parameter. And third, behind the scenes, you are using huge (in file size) interop assemblies just to make one method call.C# 4.0 will allow you to write the code above in a much simpler form that ends up looking almost exactly like 'normal' C# code. This is accomplished by using some of the features already discussed; namely dynamic support and optional parameters.HideCopy Code// Again, simplified for example.using Microsoft.Office.Interop.Word;

var doc = Application.GetDocument("MyFile.txt");doc.CheckSpelling();What will also happen behind the scenes is that the interop assembly that is generated will only include the interop code you are actually using in your application. This will cut down on application size tremendously. My apologies in advance for this weak COM example, but I hope it got the point across.ConclusionThere are some great enchantments coming in C# 4.0. This article was intended to provide an overview of the new features and why they were created. There may be some last minute tweaks to the final product, but the features above are coming and should make a big difference in your future development.History 7/1/2009: Initial version. 8/12/2009: Added moredynamicand variance samples.