Friday, February 27, 2009

C# 4.0 : Optional Parameters


C# 4.0 : Optional Parameters

Days of creating multiple overloads to avoid parameters are gone. You no more have to create many methods and pass the default one there. C# 4.0 brings to us the concept of “optional” parameters.

How it works, let’s check it. Suppose you have a method like below,

public static class TestClass


public static void ParamMethod(string Name, double Salary,

string Department, int Age = 30)


Console.WriteLine("Name = {0}", Name);

Console.WriteLine("Age = {0}", Age);

Console.WriteLine("Salary = {0}", Salary);

Console.WriteLine("Department = {0}", Department);



Here you have mentioned the default value using “=” for the parameter “Age”.

Rule!!! You always have to put optional parameters after the “non-optional” parameters.

Now if you write the below code and call the method ParamMethod, you can omit the “optional parameter” Age.

class Program


static void Main(string[] args)


TestClass.ParamMethod("Wriju", 1000.00, "Software");



Will give you the below output,

Name = Wriju

Age = 30

Salary = 1000

Department = Software


Posted: Saturday, February 28, 2009 2:44 AM by wriju

Wriju's BLOG : C# 4.0 : Optional Parameters

No comments:

Blog Archive