Click here to Skip to main content
11,490,801 members (77,040 online)
Click here to Skip to main content

C# 4.0 Features

, 6 May 2009 CPOL 59.7K 69
Rate this:
Please Sign up or sign in to vote.
This article demostrates some of the exciting features in the upcoming C# 4.0.

Introduction

After watching Anders Hejlsberg’s session, The Future of C# on Channel 9, I was excited to get my hands on the upcoming features of C#. Since the inception of C#, each version bought some major changes and amendments in the language. For example, 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 the upcoming C# 4.0:

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

Today, we will see the first two features, i.e. Dynamic Typed Object, Optional Parameters and Named Argument. A document related to New Features in C# is available at MSDN that explains all of the above features in a little detail. Plus if you are interested in getting an early look at Visual Studio 2010 CTP, you can follow my post on Visual Studio 2010 CTP. Please note that this article is written using CTP version. The final product and its features may change upon final release.

Dynamic Programming

C# 4.0 supports Dynamic Programming by introducing new Dynamic Typed Objects. The type of these objects is resolved at run-time instead of at 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 it's resolved at run-time. Let’s do some coding to see the advantage of Dynamic Typed Objects. Smile | :)

A year ago, I wrote a code of setting the property of an object using Reflection:

   1:  Assembly asmLib= Assembly.LoadFile(@"C:\temp\DemoClass\bin\Debug\DemoClass.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 lines 3-5 create 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:

Slide

From the above slide, you can call method(s) such as x.ToString(), y.ToLower(), z.Add(1), etc. and it will work smoothly. Smile | :)
This feature is great and provides much flexibility for developers. 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.

Optional Parameters

The second feature is Optional Parameters. Let’s say I have a class Employee and I provide few overloads of the constructor to enable making 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 as follows:

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

As simple as that Smile | :) and you can easily call that as follows:

Employee(“Adil”,”Mughal”);

This feature was available in some other languages but was for some reason not provided in C# yet, but now it’s available. This feature has a 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 emp= newoyee("Adil", "Mughal");

Simple but useful feature!

Named Argument

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

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

And I can simply call that as shown below:

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

A question can be raised "Is there any way that we can skip qualification, i.e. third parameter and give the last parameter of middleName?"

The answer of this question is "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. Smile | :) . Now let’s make 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");

Conclusion

These upcoming features are really cool as they will enable C# developers to be more productive with the help of dynamic programming and optional parameters though some of the features are not new in the programming languages’ world.

History

  • 5th May, 2009: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Adil Mughal
Software Developer (Senior)
Australia Australia
Adil is an aspiring software craftsman. He is currently working as Senior Developer at Nintex and has extensive experience on designing and developing enterprise scale applications on Microsoft .NET Framework. Lately he is into cross platform mobile app development on Windows, Android and iOS.
Besides, day to day job, he is active in offline and online technical communities and often participates as speaker in technical events.
He blogs about his experience at http://www.AdilMughal.com
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 5 Pin
rama charan12-Jul-12 20:25
memberrama charan12-Jul-12 20:25 
GeneralMy vote of 5 Pin
qadirv28-Jan-12 5:26
memberqadirv28-Jan-12 5:26 
QuestionLINQ Result as DYNAMIC Pin
sudheer muhammed19-Apr-11 21:01
membersudheer muhammed19-Apr-11 21:01 
GeneralNice Article Pin
arpitgold2-Apr-11 4:21
memberarpitgold2-Apr-11 4:21 
GeneralNice and easy to understand... Pin
SkGyan13-May-09 20:13
memberSkGyan13-May-09 20:13 
GeneralVisual basic no thanks Pin
Stanley Gillmer12-May-09 4:22
memberStanley Gillmer12-May-09 4:22 
GeneralPurpose of named arguments Pin
Boudino11-May-09 22:41
memberBoudino11-May-09 22:41 
AnswerRe: Purpose of named arguments Pin
tomi_212-May-09 0:03
membertomi_212-May-09 0:03 
GeneralRe: Purpose of named arguments Pin
Boudino12-May-09 1:02
memberBoudino12-May-09 1:02 
GeneralRe: Purpose of named arguments Pin
tomi_212-May-09 2:07
membertomi_212-May-09 2:07 
GeneralRe: Purpose of named arguments Pin
ronaldhobbs12-May-09 4:14
memberronaldhobbs12-May-09 4:14 
GeneralRe: Purpose of named arguments Pin
ssrdjan12-May-09 4:28
memberssrdjan12-May-09 4:28 
GeneralRe: Purpose of named arguments [modified] Pin
horia6712-May-09 6:04
memberhoria6712-May-09 6:04 
GeneralNice and Easy to Understand Pin
Member 29924898-May-09 22:01
memberMember 29924898-May-09 22:01 
GeneralRe: Nice and Easy to Understand Pin
Adil Mughal8-May-09 22:21
memberAdil Mughal8-May-09 22:21 
GeneralI very liked the "Optional and Named Parameters" feauture Pin
Reuven2228-May-09 3:40
memberReuven2228-May-09 3:40 
GeneralGood one.. Pin
Abhishek Sur7-May-09 1:41
memberAbhishek Sur7-May-09 1:41 
GeneralRe: Good one.. Pin
Adil Mughal7-May-09 2:30
memberAdil Mughal7-May-09 2:30 
Generalgood one! Pin
Jason Law6-May-09 23:39
memberJason Law6-May-09 23:39 
GeneralRe: good one! Pin
Adil Mughal7-May-09 2:28
memberAdil Mughal7-May-09 2:28 
GeneralPowered by PHP Pin
adatapost6-May-09 16:47
groupadatapost6-May-09 16:47 
GeneralRepeat Pin
PIEBALDconsult6-May-09 15:43
memberPIEBALDconsult6-May-09 15:43 
Did you miss this[^]?
GeneralRe: Repeat [modified] Pin
Adil Mughal6-May-09 16:54
memberAdil Mughal6-May-09 16:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 6 May 2009
Article Copyright 2009 by Adil Mughal
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid