What Are Optional Arguments In C#

In this blog, I will demonstrate how to implement Optional Arguments inside Methods in C#
 
Optional Arguments are the arguments which can be omitted if we do not want to change the default parameter value. Optional Arguments are defined at the end of the parameter list. There may be any number of Optional Arguments in a method.
 
Example of Optional Arguments,
  1. using System;  
  2.   
  3. namespace Tutpoint  
  4. {  
  5.     class Program  
  6.     {  
  7.         static void Main(string[] args)  
  8.         {  
  9.             Console.WriteLine("hello Tutpoint");  
  10.               
  11.             ///Call the method by omiting Optional Arguments  
  12.             Program.Details(1,"Shubham");  
  13.               
  14.             ///Call the method by omiting 'course' Optional Arguments  
  15.             Program.Details(2, "Rishabh", 11);  
  16.               
  17.             ///Call the method with all the parameters that will override the default values  
  18.             Program.Details(3, "Anuj", 12, "Art");  
  19.             Console.ReadLine();  
  20.         }  
  21.   
  22.         ///Method used to write students details with parameters as roll_No,name,id and course.  
  23.         ///Here parameter id and course have been assigned with a default value, so these are the Optional Arguments  
  24.         public static void Details(int roll_No, string name, int id=10, string course="Btech" )  
  25.         {  
  26.             Console.WriteLine(string.Format("Roll No.: {0}, Name: {1}, id: {2}, Course: {3}",roll_No,name,id,course));  
  27.         }  
  28.     }    
  29. }  
Here, Details() is a method that contains two Optional Arguments as (id, course). All Optional Arguments must have a default value. So If we skip the Optional arguments while calling the method then the method will automatically take the default value of them.
 
Note

We can not skip one or more arguments in between other arguments as shown below, this will produce an error,
  1. Program.Details(2, "Rishabh""11");  
This is incorrect and produces an error as Argument 3: Cannot convert from 'string' to 'int'
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now