C# Optional Parameter

How to use Optional Parameters in Method?

An optional parameter has a default value. A method with an optional parameter can be called with only some of its parameters specified.

Following two code snippet shows how to work with optional parameters in C#.

(1)

public void method(int a, string optParam="defaultValue")
{
      //Appropriate code here;
}

In above example second string parameter optParam is passed with default value "defaultValue".
When method() is called with only one parameter then second parameter automatically assigned to its default value.
     method(25);  // here second parameter gets value "defaultValue".
          or
   method(25,"Example"); //here second parameter gets value "Example".

Other method to pass optional parameter is,

(2)
using System.Runtime.InteropServices;

public void method(int a, [Optional] string optParam)
{
  //Appropriate code here;
}

Comments

Popular posts from this blog

SaveSetting and GetSetting in C#