Posts

Showing posts from September 6, 2010

C# 4.0 Feature - Optional Arguments

The feature that we are discussing today is called as “Optional Arguments”. Prior to C#4.0, whenever we need to pass optional parameters for a method, we used to use method overloading . For eg: private int Add(int i) { return i + 2; } Now if the Add method wanted to accept two parameters then we used to write as follows private int Add(int i, int j) { return i + j; } Now if the Add method wanted to accept two parameters then we used to write as follows private int Add(int i, int j, int k) { return i + j + k; } Eventually we had to write three overloaded methods based on the number of parameters passed and invoke the method based on the parameters passed. In C#4.0, we can rewrite the code by declaring parameters as optional as follows private int Add(int i, int j = 1, int k = 0) { return i + j + k; } When invoking this method and need only one parameter to be passed use it as