C# 4.0 + Visual Studio 2010 Beta + Windows 7 RC

Here we are with the Visual Studio 2010 Beta installed on Windows 7 RC, the most coolest and latest stuff out yet 🙂

In this post, I wanted to share some glimpse at Visual Studio 2010 beta along with some demonstration of one of the feature of C# 4.0 🙂 For Windows 7, I will write another detail post about the new features and what I like most and why it can be the best windows till yet!

So, coming back to VS 2010, If you start Visual Studio 2010 Beta, you will notice a major change in UI of Visual Studio with a nice, interactive and customizable startup page :

VS 2010 Beta Start up

Yes, It’s UI is built on Windows Presentation Foundation (WPF). So let’s go ahead and create a new project:

As you can see we have a similar kind of option, as in VS 2008, is available to select target framework version which is by default 4.0 🙂 and as you can see we have Silverlight templates available so now no need to install separate Silverlight 2 tools for VS :). Let’s move forward and create a new C# Console Application:

You will notice that editor itself is in WPF along with the intellisense menu but works almost as identical. So let’s try one of the feature of C# 4.0 🙂

I’m going to implement a method that takes dynamic typed object and that object will invoke a method which will be resolved at runtime!


Didn’t get? Keep reading 🙂 Here we have a DemoCSharpFeature class that have a static method having a dynamic parameter “obj”. Now inside that method, I have written obj.ABC() which can be resolved only at runtime because at compile time, compiler does not know what will be the actual type and it will be resolved dynamically at runtime and hence compiler will not raise a compile time error here 🙂

I have created another DemoClass which have method ABC.

Main Method 

As you have noticed that I have created an object of DemoClass which contains method “ABC” and passed to CheckDynamicParameter. The demoObj parameter will be resolved at runtime and it will find ABC method in it. Thanks to dynamic type in C# 4.0, otherwise I would have used Reflection here or static typed object 🙂

Let’s hit F5!


The beauty is that even if I remove method ABC from DemoClass, the program will still compile because it will expect that when dynamic is resolved at runtime it will find the method ABC and if not found, a Runtime Binder Exception would raised.

That’s all for today! If you want to download Visual Studio 2010 Beta, visit Visual Studio on MSDN

Implicit/Explicit Implementation of Interface in C#

In C#, we have two ways to implement interfaces:

  1. Implicit Implementation
  2. Explicit Implementation

To see the difference, Let’s say we have an interface:

public interface IDemoInterface
string Name { get; set; }
void DemoMethod();

As we implement this interface, we will notice that Visual Studio or Visual C# Express gives us an option like

If we select Implement Interface ‘IDemoInterface’ (which is implicit one) we will see the generated code like:

class Class1 : IDemoInterface

#region IDemoInterface Members

public string Name
{ //some implementation }
{ //some implementation }

public void DemoMethod()
//method implementation


whereas in contrast if we have selected Explicitly implement interface then we would have seen an implementation like

class Class2 : IDemoInterface
#region IDemoInterface Members

string IDemoInterface.Name
get { //some implementation }
set { //some implementation }

void IDemoInterface.DemoMethod()
//method implementation


So you must have noticed that in explicit implementation, the interface name is explicitly mentioned with the property and the method but of course that is not the only difference 🙂

Then what does it mean? and what is the real difference?

Well explicit implementation allows the interface members to be accessible only when the object is cast to interface type 🙂 Means that when I will instantiate an object of Class 1, I will be able to access interface members in contrast to Class 2 in which I have to cast the object to that particular interface. Not clear, consider the code below:

In contrast, when you create object of Class 2 you will not be able to see Interface members

until or unless you cast that object into interface type…


When interface members are explicitly implemented, they are not accessible through class instance instead through interface instance.

Beside this another noticeable point is that when implemented explicitly the members’ name become InterfaceName.MemberName and hence multiple interfaces with same member name can implement in the class whereas this is not possible in the implicit implementation. A disadvantage of Explicit implementation is that when used with value types, Boxing can cost performance.

Deleting Duplicate Files Programmatically

Last week I downloaded Mix 09 videos from Mix 09 Videos Online and that was around 7 GB. As we are distributing Mix 09 DVDs on our upcoming INETA user group meeting of Emerging .NET Devs, so what I did is that I selected and copied some videos into another folder and burn that folder in DVDs. And that was great, work done! 🙂

As a result of that, I have duplicate data which was taking some GBs on my laptop HD. Also I don’t want to delete the folder with selected videos as I may need to burn again. So I concluded that I need to have intersection of two folders to avoid duplication. There were more than 60 files and I don’t want to manually match the file and delete redundant files.

Why on earth I will do that manually, just write a program of few lines in .NET and done! Hence I wrote a program which perform a kind of intersection of files in two folders 🙂 something like:

string path = @"C:UsersADILDesktopMix 09";
string pathInnerFolder = @"C:UsersADILDesktopMix 09Mix 09";
DirectoryInfo dir = new DirectoryInfo(path);

foreach (var file in dir.GetFiles())
if (File.Exists(pathInnerFolder + "" + file.Name))

It worked! Excellent! I’m becoming Geek 🙂

Most Popular Article on Code Project

cpArticle Last week I submitted an article, C# 4.0 Features, on CodeProject.com. From time to time, I have been posting some content related to C# 4.0 features on my blog, So what I did is that I formalize them as an article and submitted to code project. I shared my article with my colleagues, friends and MVPs and I got appreciation from them.

Today I received newsletter from Code Project which mentioned that my article is among most popular new articles from 4th May to 11th May 😀 with rating of 4.15/5.


Great, isn’t it? So that really boosts me up and hopefully I will continue writing articles on my blog, User Group blog and on different websites. To visit my profile on CodeProject, click here.

C# 4.0: Named Argument

Okay, we saw Optional Parameters, an upcoming feature of C# 4.0, in the last post and one reader of my blog asked me a question related to “Optional Parameters”. I don’t believe I have readers of my blog as well 🙂 but that was also one of my friend :p

So, in last post, we discussed an example of Employee class in which we passed some optional parameters in constructor:

public Employee(string firstName, string lastName, string qualification = "N/A", string middleName = "")

and I can simply call that like:

Employee emp= new Employee("Adil", "Mughal");

The great question was that Is there any way that we can skip qualification i.e. third parameter and give last parameter of middleName? He seems to be good reader or he might have listened to Anders Hejlsberg’s session 😉

The answer of this question is that Yes absolutely we can and that feature is called Named Argument in C# 4.0. We can simply do this like:

Employee emp = new Employee("Adil", "Mughal", middleName: "Ahmed");

Good enough to answer the query :). Now let’s do some changes with the Employee constructor and make lastName optional as well:

public Employee(string firstName, string lastName = "", string qualification = "N/A", string middleName = "")

Now I can instantiate object of Employee in quite simple and flexible ways

Employee("Adil", qualification:"BS");
Employee("ABC", lastName: "EFG", qualification: "BS");
Employee("XYZ", middleName: "MNO");

These upcoming features are really cool as they will improve productivity of cool enough to help C# developers avoid writing ‘n’ number of overloads though some of them are not new in the programming languages’ world.

Optional Parameters in C# 4.0

In the last post we saw dynamic typed object in C# and as we saw earlier the upcoming features of C# 4.0, Today we are going to look at Optional Parameters.

Let’s say I have a class Employee and I provide few overloads of constructor to enable make certain parameters as optional as follows:

 public class Employee
public string FirstName { get; set; }
public string LastName { get; set; }
public string Qualification { get; set; }
public string MiddleName { get; set; }

public Employee(string firstName, string lastName)
FirstName= firstName;
LastName= lastName;
Qualification= "N/A";
MiddleName= string.Empty;
public Employee(string firstName, string lastName, string qualification)
FirstName= firstName;
LastName= lastName;
Qualification= qualification;
MiddleName= string.Empty;

public Employee(string firstName, string lastName, string qualification,
string middleName)
FirstName= firstName;
LastName= lastName;
Qualification= qualification;
MiddleName= middleName

With C# 4.0, you need to create just one constructor for that and that is

public Employee(string firstName, string lastName,
string qualification = "N/A", string middleName = "")
FirstName= firstName;
LastName= lastName;
Qualification= qualification;
MiddleName = middleName;

as simple as that 🙂 and you can easily call that like Employee(“Adil”,”Mughal”);

This feature was available in some other languages but was for some reason not provided in C# till yet but now it’s available. This feature has good impact in COM interop which allows developers to skip missing parameters which we will hopefully see in later post(s). Finally, the compiler will always fill the optional parameters by their default given values, if you do not provide them. For instance, In our current case it will be:

Employee(“Adil”, “Mughal”, “N/A”, “”);

Simple but useful feature!

Dynamic Programming in C# 4.0

C# 4.0 supports Dynamic Programming by introducing new Dynamic Typed Objects. The type of these objects is resolved at run-time instead of compile-time. A new keyword dynamic is introduced to declare dynamic typed object. The keyword tells the compiler that everything to do with the object, declared as dynamic, should be done dynamically at the run-time using Dynamic Language Runtime(DLR). Remember dynamic keyword is different from var keyword. When we declare an object as var, it is resolved at compile-time whereas in case of dynamic the object type is dynamic and its resolved at run-time. Let’s do some coding to see advantage of Dynamic Typed Objects 🙂

A year back I wrote a code of setting property of an object using Reflection:

   1:  Assembly asmLib= Assembly.LoadFile(@"C:tempDemoClassbinDebugDemoClass.dll");
2: Type demoClassType = asmLib.GetType("DemoClass.DemoClassLib");
3: object demoClassobj= Activator.CreateInstance(demoClassType);
4: PropertyInfo pInfo= demoClassType.GetProperty("Name");
5: pInfo.SetValue(demoClassobj, "Adil", null);
Notice line 3-5 creates instance of ‘demoClassType’ and set property ‘Name’ to ‘Adil’. Now with C# 4.0 line # 3-5 can be written as simple as:

dynamic dynamicDemoClassObj = Activator.CreateInstance(demoClassType);
dynamicDemoClassObj.Name = "Adil";
Simple isn’t it? Let’s see a slide from Anders Hejlsberg’s session at PDC 2008:


From the above slide, you can call method(s) such as x.ToString(), y.ToLower(), z.Add(1) etc and it will work smoothly 🙂

This feature is great and provides much flexibility for developers. In this post, we explore the dynamic typed object in C# 4.0. We will explore dynamic in detail and other features as well in the coming posts. Of course there are pros and cons of dynamic programming as well but where C# is going is something like having features of both static languages and dynamic languages.

C# 4.0

After watching the Anders Hejlsberg’s session “The Future of C#” on Channel 9, I’ve got excited to get hands on the upcoming features of C#. Since the inception of C#, each version bought some major changes and amendments in the language. Like, In C# 1.0 the major theme was Managed Code then in C# 2.0, Generics were introduced and lastly in C# 3.0 LINQ was introduced. C# 4.0 introduced the concept of Dynamic Programming in C#. Overall there are four main features that are introduced in upcoming C# 4.0:

  1. Dynamic Typed Objects
  2. Optional and Named Parameters
  3. Improved COM Interoperability
  4. Co- and Contra-Variance

We will explore these features one by one in the upcoming posts. A document related to New Features in C# is available at MSDN that explain all of the above features in a little detail. Plus if you are interested in getting an early look on Visual Studio 2010 CTP, you can follow my post on Visual Studio 2010 CTP.

Have a good time!

Using LINQ with Relational Data


Till this point we have seen LINQ To Objects and LINQ To XML. I found a great webcast on using LINQ with Relational Data by Rob Bagby, So I thought instead of explaining my way, I would recommend you to go through the webcast 🙂

MSDN Webcast: Using LINQ with Relational Data (Level 100)


In my earlier post on LINQ, we saw an example of LINQ to Objects. In this post we will see LINQ to XML example. LINQ to XML was the real reason why i attracted towards LINQ. I’m pretty excited to see what LINQ provides as compare to the old techniques. So let’s start coding 🙂

Let’s say we have an XML as below:

Now suppose that I want to get list of all employees in Microsoft. Without LINQ, I would probably load the xml in XmlDocument object and then apply XPATH with respect to the company name attribute. With LINQ, it’s easy and simple way to load xml and write a single SQL like query even for XML. For instance i want to fetch list of all employees in KalSoft,

var companies = XElement.Load("companies.xml").Elements("Company");

var queryResult = from company in companies
where company.Attribute("Name").Value == "KalSoft"
select company.Descendants();

This query selects all the descendants i.e. Employee(s) of company having Name == “KalSoft”. To obtain the output we can get the string as

foreach (var item in queryResult)
foreach (var element in item)

which will give us the desired output:


Hence, LINQ to XML provides an simpler way, to programmer, to query XML Documents based on different conditions.