Named and optional arguments in C#4.0

Discussion created by VKamakodu on Jun 11, 2009
Latest reply on Jun 16, 2009 by spilon

One of the new language features in C#4.0 is optional and named arguments. How many times have you wished to pass an argument as option in your method? You could do this in VB but not C#. Just the other day, one of my coworkers asked me if C# supports optional parameters. I said no. As you may know, the only way you could achieve the "optional" effect was by overloading C# methods (in C#3.0 and before).


But move over C#3.0, C#4.0 now supports this! So let's take a look.


Method signature:


You can notice that method parameter has the default value which makes it an optional parameter. That means arg2 and arg3 are optional paramters.


static void MyMethod (string arg1, string arg2="myString2", string arg3 = "mystring3"){};


Method Call:


As you can see below, when I am calling the method that has optional parameters, I don't have to pass anything.


MyMethod("1"); MyMethod("1","2");  - valid calls


MyMethod("1", , "3") - this is invalid


If I want to make the above a valid call, I can use the named argument like below. Notice the syntax of named argument [arg2: "2"]


MyMethod("1", arg2: "2", "3")


For more, see this msdn article http://msdn.microsoft.com/en-us/library/dd264739(VS.100).aspx