Wednesday, November 24, 2010

Named And Optional Parameters in C# 4

Optional Parameters

Optional parameters have been added to C# 4 (released earlier this year). I've seen many developer claiming for this feature since VB.NET had it; yet, I always felt more comfortable using method overloads and I am not debating that.

Optional parameters allow us to set a parameter default value.

Example:

public static void ProcessFeed(int id,string feed = "default",bool isValid=true)
 {
           //TO DO:
 }

When calling this method will get:


Example 1:
ProcessFeed(1,"myfeed",false);


Method will get the following values:
  id = 1
  feed = "myfeed"
  isValid = false


Example 2:
ProcessFeed(2);



Method will get the following values:
  id = 2
  feed = "default"
  isValid = true

Named Parameters

Named parameters allow us to skip parameter that have default values. 
For example, if we want to use the default value of feed but change the value for isValid we would have to call the following:

Example 3:
ProcessFeed(3,"default",false);

or we can use named parameters which will make give us a cleaner sintax.

Example 4:
ProcessFeed(3,isValid:false);









No comments:

Post a Comment