Optional Parameter in C# Language

Introduction

Default parameter include in c# 4.0 version. You can, however, provide a code generator that creates a set of overloads from a declaration containing default arguments. Optional parameters are defined at the end of the parameter list, after any required parameters in a function. When you call to a function and you are not pass other value to default. Then default parameter value use in a function.

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

namespace optional_parameter_in_c_sharp

{

    class parameter //create class

    {

        //create a function with two parameter, x and y, where y assign default value 5.5

        public double sum(double x, double y = 5.5)

        {

            return x + y;  //return sum of x+y

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            parameter obj = new parameter(); //create object

               //call to sum function, when two value given to function

            Console.WriteLine("Sum of given two value: {0}\n",obj.sum(4.5,8));

              //call to sum function, when one value given to function

            Console.WriteLine("Sum of given one and other default value: {0}", obj.sum(4));

            Console.ReadLine();

        }

    }

}


Output


output.jpg