Thursday, April 29, 2010

Optional parameters on C#

If you have started with C# 4.0, this feature may seem to be very exciting. You might have already used optional parameters on SQL. The new C# 4.0 has the capability to have optional parameters on our application code. Let’s look at how to use this feature.

Create a console project.

Copy the below code

static void Main(string[] args)

{
      Program.CreateUser(lastName: "padubidri", firstName: "subramanya");
      Program.CreateUser("padubidri", "subramanya");
      Program.CreateUser("padubidri", "subramanya",1001);
      Console.ReadKey();
}


private static void CreateUser(string lastName,string firstName,int userID = 0)
{
      Console.WriteLine("lastName:" + lastName + "; firstName: " + firstName + "; ID: " + userID);
}

Observe the method CreateUser where I have default value for userID. Look at the above part where this method is invoked. When we don’t send userID parameter, it takes the default value. On Main method you can observe the different ways you can call this createUser method. Just remember that if you specify parameter name when you invoke the method, your dll or exe might break if the parameter name is changed in the future. So the second and third lines on the above call are safer way to deal with.



Let’s run this code and look at the result.


The first two calls taken userID 0 which is default value.


You can also use the optional parameters on interfaces. I feel this would help us to avoid lots of overload methods but it might also have evil effect if we don’t use this correctly.

No comments:

Post a Comment