C# optional arguments

C# allows us to limit the number of arguments passed to a function but using optional arguments in function definition.

The optional arguments assign a default value for the argument that is not passed in the function call.

As per rule, the required arguments should come first, and then the optional arguments can be used.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication6
{   
    class Program
    {
   
        static void Main(string[] args)
        {
            int num1 = 10;
            int num2 = 20;
            TestMethod(num1, num2);

            TestMethod(num1);
        }

        static void TestMethod( int notOptionalNumber, int optionalParameter = 10)
        {
            Console.WriteLine("{0}, {1}", optionalParameter, notOptionalNumber);
        }

     

     
    }
}

 

Add a Comment

Your email address will not be published. Required fields are marked *