65.9K
CodeProject is changing. Read more.
Home

An Introduction to Named Parameters - C#4.0

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.72/5 (15 votes)

Oct 25, 2010

CPOL

1 min read

viewsIcon

30571

downloadIcon

63

TThis article will tell about the advantage of using named parameter

Introduction

C#4.0 has bring the new Named Parameter in its collection to give developers the flexibility of applying the parameters at their own discretion.

Background:

Consider the below example which is done in in a lower version of .Net

class Program
    {
        static void Main(string[] args)
        {
            WithoutNamedParameter(10, "SomeName");
            WithoutNamedParameter("SomeName",10);
            Console.ReadKey(true);
        }

        private static void WithoutNamedParameter(string name, int age)
        {
            Console.WriteLine(string.Format("{0},your age is {1}", name, age));
        }

        private static void WithoutNamedParameter(int age, string name)
        {
            Console.WriteLine(string.Format("{0},your age is {1}",name,age));
        }
    }

As can be seen that the function WithoutNamedParameter is a simple overloaded method where it accepts only 2 parameter and that too of same type (int and string) with the only difference that the order is changed. Though the output will be same in both the case.

This happens in real time scenario and the developer had no option but to create a overloaded method.

C#4.0 has culminated the problem by the introduction of Named parameter where the developers has the flexibility of using the parameters.

Overloaded problem solved using Named Parameter

Now let us see how C#4.0 has overcome such situation. Consider the below program

class Program
    {
        static void Main(string[] args)
        {
            #region Named Parameter Example
            WithNamedParameter(Age: 10, Name: "SomeName");
            WithNamedParameter(Name: "SomeName", Age: 10);
            Console.ReadKey(true);
            #endregion
        }

        private static void WithNamedParameter(string Name, int Age)
        {
            Console.WriteLine(string.Format("{0}, your age is {1}", Name, Age));
        }
    }

As can be seen that in the WithNamedParameter it is just the Parameter name that we are specifying in the method call followed by a colon( : ) and then the parameter value while the compiler does the rest. Is not that handy?

The output is as expected

3.jpg

Conclusion:

In this short article we have seen how named parameter help developers to avoid writing overloaded methods and rather helps in code reusability.

Comments on the topic are highly appreciated for the improvement of the topic.

Thanks for reading the article.