C# Language Optional Arguments


Example

Consider preceding is our function definition with optional arguments.

private static double FindAreaWithOptional(int length, int width=56)
       {
           try
           {
               return (length * width);
           }
           catch (Exception)
           {
               throw new NotImplementedException();
           }
       }

Here we have set the value for width as optional and gave value as 56. If you note, the IntelliSense itself shows you the optional argument as shown in the below image.

enter image description here

Console.WriteLine("Area with Optional Argument : ");
area = FindAreaWithOptional(120);
Console.WriteLine(area);
Console.Read();

Note that we did not get any error while compiling and it will give you an output as follows.

enter image description here

Using Optional Attribute.

Another way of implementing the optional argument is by using the [Optional] keyword. If you do not pass the value for the optional argument, the default value of that datatype is assigned to that argument. The Optional keyword is present in “Runtime.InteropServices” namespace.

using System.Runtime.InteropServices;  
private static double FindAreaWithOptional(int length, [Optional]int width)
   {
       try
       {
           return (length * width);
       }
       catch (Exception)
       {
           throw new NotImplementedException();
       }
   } 

area = FindAreaWithOptional(120);  //area=0

And when we call the function, we get 0 because the second argument is not passed and the default value of int is 0 and so the product is 0.