Saturday, 13 April 2013

What's New in C# 4.0


Below are new features introduced in c#4.0 with example:
1.       Dynamic Lookup: It resolves types in a program at runtime. It’s very useful in below scenarios:
a.       Office Automation or COM Interop scenarios.
b.      Consuming types written in dynamic languages (like IronPython, IronRuby…)
c.       Call Reflection : currently we use Reflection to instantiate a class when a types is not known at compile type.
Example:


2.       Named and Optional Parameters: Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter's name rather than with the parameter's position in the parameter list. Optional Parameters enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors, and delegates.
Example:

3.       Covariance and Contravariance: covariance and contravariance refers to the ordering of types from narrower to wider and their interchange ability or equivalence in certain situations (such as parameters, generics, and return types). (Source- Wikipedia).
Types that are
·         covariant: converting from a specialized type (Cats) to a more general type (Animals): Every cat is an animal.
·         contravariant: converting from a general type (Shapes) to a more specialized type (Rectangles): Is this shape a rectangle?
Example:
Covariance:

If you see above example here, you will find two interesting point here inside Main method. If you try to compile this program in .Net Framework 3.5 or less you will get error in second line of Main method saying “An explicit conversation exist (are you  missing a cast?)”.
IEnumerable<Person> persons = new List<Employee>();
It’s really surprising, If a base class called Person can hold the object of his child class called Employee, then why this is not applicable in with group of objects. SO this is where C#4.0 introduced a feature called Covariance. SO if you compile it under C# 4.0 compiler you will not get any error.
So the result here is: Covariance preserves assignment compatibility.
ContraVariance:

In above example, I have an overloaded method called PrintPerson. If you compile above code in C# 3.5 or less version you will get error on last line of code.
IEnumerable<Employee> empList = new List<Employee>();
PrintPerson(empList);
But in C# 4.0 or later version it works fine. SO this is where C#4.0 introduced a feature called Contravariance.

4.       COM Interop Enhancement.
In C# 4.0, calling COM object become more easier. For an example let’s talk about Microsoft.Office.Interop.Word. We will write a code to open a word file in C# 3.5 and C#4.0 and then we will see what’s enhancements is done in C#4.0.


If you see the above code here, it says itself about the enhancement of COM Interop library. Writing code become more easier than earlier version of C#.

Thank You for reading. Feel free to give your feedback.