Monday, 13 November 2017

Optional Parameters in C#.

In this article, We will discuss How to use Optional Parameters in C# and also Why to Use Optional Parameters in C#.

As the name Suggests, Optional Parameters means we can pass Optional Values to Parameters in Function or methods.

Let us take an example to explain Optional Parameters,

Example:-

private void Test(string Lname,string Fname="James")
{
//rest of code
}


When i call this method Test(), then at that time Lname we need to pass and for Fname either we can pass or we cann't pass the value in it.

So we can call Test() like this,

Test("Evans"); // Here by default James take as Fname
Test("Evans","Chris"); // Here "Chris" take as Fname


We need to Use Optional Parameters, when we need to pass some default values in it.


Even if We can use [Optional] Keyword in Function defination like this and Which works Same.

private void Test(string Lname, [Optional] string Fname = "James")
        {
//rest of code
        } 


Note:- To Use [Optional] you need to include this namespace using System.Runtime.InteropServices;

1 comment:

  1. Very informative post for student..!

    Optional Parameters in C# (good content to learn & practice)

    hire sharepoint developers
    hire sharepoint programmer

    ReplyDelete