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,
- using System;
-
- namespace Tutpoint
- {
- class Program
- {
- static void Main(string[] args)
- {
- Console.WriteLine("hello Tutpoint");
-
-
- Program.Details(1,"Shubham");
-
-
- Program.Details(2, "Rishabh", 11);
-
-
- Program.Details(3, "Anuj", 12, "Art");
- Console.ReadLine();
- }
-
-
-
- public static void Details(int roll_No, string name, int id=10, string course="Btech" )
- {
- Console.WriteLine(string.Format("Roll No.: {0}, Name: {1}, id: {2}, Course: {3}",roll_No,name,id,course));
- }
- }
- }
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,
- Program.Details(2, "Rishabh", "11");
This is incorrect and produces an error as Argument 3: Cannot convert from 'string' to 'int'