Optional Arguments

suggest change

Consider the following function definition with an optional argument.

private static double FindAreaWithOptional(int length, int width = 56)
       {
           return length * width;
       }

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.

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.

Using Optional Attribute.

Another way to mark an optional argument is the [Optional] attribute. If you do not pass that argument, the default value of its type is assigned. [Optional] is in the System.Runtime.InteropServices namespace.

using System.Runtime.InteropServices;  
private static double FindAreaWithOptional(int length, [Optional] int width)
   {
       return length * width;
   } 

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents