February 27, 2009

C# 4.0 New features – Optional/Default values in Method calls

Filed under: C# 4.0 — @ 7:18 pm

I been wanting this feature in C# for some time. I am happy they are going to implement it in C#4.0. Even though C# has some very new cool features, I think this is one of the feature that ordinary programmer would use everyday. There are times I do not want pass a parameter to a method. If the parameter is not passed, I want it to get a default values. In C#3.0 we can not do it. The solution to this problem is to write wrappers for each missing parameters and then assign the default value and then call the actual method. It was ok, but too many Unit tests and add more lines of code for possible bug somewhere.

With this new feature we can get the best of what other languages were enjoying for sometime. Lets look at a example

public class Personal


        public int GetEmployeeListing(string name = “*”,

                       int age = 20,

                      char sex = ‘f’)




   static void Main()



      Console.WriteLine(GetEmployee(sex:’m’, age=25);



As you can see in the above example, ‘GetEmployeeListing’ takes 3 parameters and all of them have default values. So in the Main when we invoke the write WriteLine method, we passed only the age field, thus using name and sex to default value. The second call shows one additional benefit of this definition, parameters are not absolute anymore once you name them. In this case, we change the order and passed sex and age so when the program it name will take the default value.

Of all the features I read, this one will be the one used heavily but again, it is too soon to guess anything.

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress