C# is a language we work on regularly, it is a language that we love the most. It is always good to see updates to such a lovely language which is very common to most of us. C# 4.0 after its release, comes with certain features that I think would love to know about. In this article I have discussed these common facts on C# 4.0 updates which you might find interesting.

Introduction

C# as a language is getting richer day by day whilst we are introduced with newer releases of .NET framework. Recently pronounced .NET 4.0 comes with lots of new features on different aspect of programming world. Some relates to technology, while some directly changes the basic API of the language structure. C# as a language is not deprived from those changes, and hence it is time to go on and understand few of the basic changes that are made in the C# language.

In this article, I will introduce the basic changes to C# 4.0. To start lets jot down the topics which I will discuss in this article first.

Named and Optional Parameters

Dynamic Keyword

Co-Variance and Contra-Variance

Event Object Locking Changed

These are not the only feature that is introduced with .NET 4.0. There are lots of others too. But to start with it, in this article I have talked about these heads. We will talk about others later on. Lets get started.

Named and Optional Parameters

C# didn't have Optional Parameters that VB.NET had for a long time. One who is coming from VB or VB.NET will definitely miss this feature. Lets start with Optional Parameter first. See the code :

n the above code, the call to MyFunctionWithOptionalParameter will return "Will take optional parameter as 10" as we have the second parameter y made as optional. Now if we want similar functionality in C# we need to write like this :

Therefore you can see we have actually created an overload which automatically places 10 for us in C#, which is actually unnecessary in most of the cases. Therefore you can say C# was having less flexibility than VB.NET.

So you can see, IL for the code also looks different. It is not actually an overload of method in VB.NET. Thus you can say, Optional parameter is already in the MSIL, but it is not exposed to C#.

C# 4.0 exposes this feature. In C# you can use Optional parameter as you can do in VB.NET for a long time.

Named parameters on the other hand lets you to specify parameters by Name. Many developers gets bored by knowing the exact sequence of parameter list. Sometimes one class takes string as first argument while another overload takes integer as first argument. Looking at such code is really horrendous. C# 4.0 introduces the new feature which lets you specify the name of the parameter while calling it using a colon (":"). Let us look how these two features looks like :

Thus with the one constructor you have eventually created all the 4 types of constructors. You should note that, you cannot skip optional parameter. If you want to do so, you need to use NamedParameter to specify the actual parameter name before you specify the argument.

You cannot skip any optional parameter without calling by their names. This I already discussed above.

Dynamic Keyword

After the introduction of "var" in C# 3.5, the use of anonymous types increased rapidly. But as C# doesn't truly supporting the dynamic types, which means the types will be determined during the runtime and any error that is produced will not affect compilation of the project, there were lots of limitations. var is determined during compile time, and it is implicitly typed variable so it cant be a return type of a method. dynamic on the other hand can be a part of return type or argument of a method and will act during runtime when actual object is set to it.

Let us look on the code below :

Here the dynamic object is created and a method is invoked. As this is truly dynamic, everything will be evaluated in runtime and hence you can call CallMe or even CallMe2(which is not present) during compile time and this will evaluated during runtime and produce errors.

Dynamic keyword is COM friendly, as everything is done during runtime using reflection, it can also handle com interfaces as and when passed to it.

Limitation

If you delve deep into what exactly happening on dynamics, as I wondered that compiler is actually not capable of creating true dynamic allocation, I saw this :

So you can see the compiler is actually using Reflection to invoke the members for dynamic types. The dynamic type is actually assigned to a anonymous type and then the member is invoked. So if you assign a value type on a dynamic object it will box and unbox for you.

Co-Variance and Contra-Variance

If you are coming from Mathematics or rather statistics, you must have already know the terms, co-variance and contra-variance. The co-variance means when one variable is changing another will also change accordingly. In case of Generics in C#, Variance exists but you cannot employ restriction of variance through the compiler.

the error will be sorted out for time being, but eventually during runtime it will again throw this error. This is because of the fact List is not a List. This restriction is given to C# to ensure type safety. How? Yes, say you have Mercury inherited from IPlanet. Now if you want List can be assigned to List, you can easily add a Mercury to the List of earth. Thus it violates type safety. Does it have a solution? Yes, C# 4.0 has a solution. With the introduction of Co-variance keyword out, you can restrict a collection to have only read permission to the collection. So this ensures that when you assign a List to a List you cannot insert an object of Mercury to it simply by dereferencing at a position.

So based on our motto we declare :

Now using C# 4.0 we can create the similar thing. Let us look the new version :

The generic type parameter for the interface IMyList gets an out T parameter where T is restricted to IPlanet. That means the interface IMyList is instructed to generate any types under the IPlanet family and IPlanet can only appear in output position of the class IMyList. So if you now want to add a Mercury object to IMyList the compiler will apply coercive conversion of Mercury to Earth, and hence it will not allow this. Hence, it solves the problem of type safety and thus allows co-variance.

On the contrary, Contra-Variance is just an opposite to Co-variance. Contra-variance enables you to create interfaces or delegates where the Types can only come in input parameters, such as argument to a method etc. To make it clear, let us make it simple using IComparer which is actually redefined in C# 4.0 to have contra-variance.

myEarthlist.Sort(new LengthComparer()); //where mylist is a list of Earth

It will give a nasty error in less than C# 4.0 like :

cannot convert from 'DemoApp.Class1.LengthComparer' to 'System.Collections.Generic.IComparer'

In C# 4.0, the IComparer is restricted to only contain variables in input positions and hence it allows to compare list of earth with the same class as LengthComparer.
Contra-variance restrict the class to create object, rather it can only compare two objects passed into it. As it cannot create objects, type safety is guaranteed and it means you cannot have two objects as Mercury and Earth.

So in a nut shell, if you specify for an interface, you can only have T in output position. If you want to send T as argument of any method you will get an error. So if I write :

public void Add(T planet)
{
}

in MyList I will get an error. Same in case of where the compiler will only allow to input T, it wont allow you to return T in output position.

Event Object Locking

If you know what happens when you try to add an EventHandler or try to remove one event handler from an Event Accessor or even a public event you might know, the compiler places an explicit object lock when the event are added or removed. This is something like lock(this).

It is always better to avoid lock(this) as say you are using multiple threads accessing same object. If you invoke lock(this) it means the object will be locked to all other threads even though another thread tries to access another portion of the code. In case of C# less than 4.0, the compiler invokes explicit lock on the object when you want to add or remove a EventHandler from code. So it will look like:

Blog Subscription

Learn MVC 5 step by step

My friend Shivprasad Koirala who is also a Microsoft ASP.NET MVP has released Learn MVC 5 step by step video series. It starts right from basics of MVC and goes to a level until you become a professional.
You can start taking the course for free using the below youtube video.
Please try it, you will find it awesome.

My Awards

Hit Counter

Twitter

Best .NET 4.5 Expert CookBook

Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
Grab it now !!!
Another book on .NET 4.5 has been released very recently. It covers Debugging, Testing, Extensibility, WCF, Windows Phone, Windows Azure and many more...
Grab it now !!!GET ANY BOOK AT $5 from PacktPub. Offer is limited