Dec 15, 2015

Use Optional Parameters For Methods In C#

In C# You Can Create Methods With Optional Parameters. Which Means, When You Are Calling The Method You Don't Need Pass All The Parameters. If You Want You Can Ignore The Optional Ones. Then Methods Will Take The Defaults Values. Important Thing In Optional Parameter Is, You Have To Give A Default Value To The Optional Parameters.

Lets See How We Can Do This. I Have Create A Simple Console Application. In That Create A Static Method Called "SayHello" Which Takes Two String Parameters As "First Name" And "Last Name".



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Optional_Parameter
{
    class Program
    {
        static void Main(string[] args)
        {
            SayHello("Nifal", "Nizar");
            Console.ReadLine();
        }

        static void SayHello(string firstName, string lastName)
        {
            Console.WriteLine("Hello {0} {1}", firstName, lastName);
        }

    }
}

If You Run This You Will Get The Output In The Console As Below.

Hello Nifal Nizar

Lets Make The "Last Name" Parameter Optional. Simply In The Method Give A Default Value To The "Last Name" Parameter. In My Case I'm Giving Empty String To It. Lets See The Code.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Optional_Parameter
{
    class Program
    {
        static void Main(string[] args)
        {
            SayHello("Nifal");
            Console.ReadLine();
        }

        static void SayHello(string firstName, string lastName = "")
        {
            Console.WriteLine("Hello {0} {1}", firstName, lastName);
        }

    }
}

Now Run And See The Output.

Hello Nifal

Same Like This You Can Make More Optional Parameters. Hope You Got The Knowledge Of Optional Parameter.


No comments:

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...