Named and optional Parameter in C#


Named and optional parameters are the one of the new features of C# 4.0. This feature allows developers to have an option to create named and optional parameters in a method.

Named Parameter

Now let see the example of Named Parameter:

NamedParameter

Complete C# code

using System;

namespace Named_OptionalParameter
{
    class Program
    {
        static void Main(string[] args)
        {
            var objPrice = new PriceClass();
            //Traditional approach to Call the method
            Console.WriteLine(objPrice.CalculatePrice(10,100,false));
            // Using Named parameter approach to call the method
            Console.WriteLine(objPrice.CalculatePrice(EliteMember:false,quantity:10,price:100));
            Console.ReadLine();
        }
    }
    public class PriceClass
    {
        public double CalculatePrice(int quantity,double price, bool EliteMember)
        {
            if (EliteMember)
            {
                return quantity * price - 10;
            }
            else
                return quantity * price;
        }
    }
}

In the above code we saw that we have created the method to calculate price and we are passing the parameter as int, double, bool as parameter. But if we will not pass in this order it will through the exception upto C# 3.0. But from C# 4.0 there is not mandatory to pass parameter as same as method defined.

We can pass parameter as per as developer desire like this
// Using Named parameter approach to call the method

Console.WriteLine(objPrice.CalculatePrice(EliteMember:false,quantity:10,price:100));

Optional Parameter

Now let see the example of Optional parameter example

OptionalParameter

If you will see in the above example, CalculatePrice Method has two parameter i.e price and eliteMember. For that parameter it is not mandatory to pass the parameter. If we will not pass the parameter then it will take default value which one we have defined in parameter.

For example, if we have to override the optional value of method then this also possible, we have to just pass the desire value in parameter as shown in above image.

Summary:

We learned that what is the named and optional parameter in C#

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.