Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#

Named and Optional Arguments In C#

Rate me:
Please Sign up or sign in to vote.
4.47/5 (6 votes)
6 Jul 2015CPOL4 min read 21K   4   2
Named and optional arguments in C#

Introduction

In this article, we will learn about two things that we must be aware of as programmers:

  • Named arguments
  • Optional arguments

Both of these have been introduced with Visual Studio 2010. Now we will go ahead in detail about those. I hope you will like it.

Background

I am working in a project in which we are using Visual Studio 2012 and C# as the programming language. We have so many functions in our logical layers. In those functions, we used both Named and Optional arguments. So I thought of sharing this with you. Please note that this article is for those who have not tried these Named and Optional arguments yet.

Before going to the coding part, we will learn what named and optional argument is? What are all the features of these two?

Named Arguments

Reference: MSDN

Named arguments enable you to specify an argument for a particular parameter by associating the argument with the parameter’s name rather than with the parameter’s position in the parameter list.

As said by MSDN, a named argument:

  • Enables you to pass the argument to the function by associating the parameter’s name
  • No need for remembering the parameter's position that we are not aware of always
  • No need to look at the order of the parameters in the parameters list of called function
  • We can specify parameter for each argument by its name

Now we will describe all about a named argument with a simple program. I hope we all know how to find out the area of a rectangle. Yes, you are right! It is A= wl (where w is the width and l is length and A is area.) So we will be using this formula in our function. Consider the following is our function call:

C#
FindArea(120, 56);

In this, our first argument is length (i.e., 120) and the second argument is width (i.e., 56). And we are calculating the area by that function. And following is the function definition:

C#
private static double FindArea(int length, int width)
       {
           try
           {
               return (length* width);
           }
           catch (Exception)
           {
               throw new NotImplementedException();
           }
       }

So in the first function call, we just passed the arguments by its position. Right?

C#
double area;
Console.WriteLine("Area with positioned argument is: ");
area = FindArea(120, 56);
Console.WriteLine(area);
Console.Read();

If you run this, you will get an output as follows:

Image 1

Now here come the features of a named arguments. Please see the following function call.

C#
Console.WriteLine("Area with Named argument is: ");
area = FindArea(length: 120, width: 56);
Console.WriteLine(area);
Console.Read();

Here, we are giving the named arguments in the method call.

C#
area = FindArea(length: 120, width: 56);

Now if you run this program, you will get the same result. Please see the below image.

Image 2

As I said above, we can give the names vice versa in the method call if we are using the named arguments, right? Please see the following method call.

C#
Console.WriteLine("Area with Named argument vice versa is: ");
area = FindArea(width: 120, length: 56);
Console.WriteLine(area);
Console.Read();

Please run the program and see the output as below:

Image 3

You get the same result, right? I hope you said yes.

One of the important uses of a named argument is, when you use this in your program, it improves the readability of your code. It simply says what your argument is meant to be, or what it is.

Now you can give the positional arguments too. That means, a combination of both positional argument and named argument. So shall we try that?

C#
Console.WriteLine("Area with Named argument Positional Argument : ");
area = FindArea(120, width: 56);
Console.WriteLine(area);
Console.Read();

In the above example, we passed 120 as the length and 56 as a named argument for the parameter width.

Image 4

I hope you enjoyed using named arguments, there are some limitations too. We will discuss the limitation of a named arguments now.

Limitation of Using a Named Argument

Named Argument Specification Must Appear After All Fixed Arguments Have Been Specified.

If you use a named argument before a fixed argument, you will get a compile time error as follows:

Named argument specification must appear after all fixed arguments have been specified.

Image 5

Optional Arguments

Reference: MSDN

The definition of a method, constructor, indexer, or delegate can specify that its parameters are required or that they are optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters.

As said by MSDN, an Optional Argument:

  • We can omit the argument in the call if that argument is an Optional Argument
  • Every Optional Argument has its own default value
  • It will take default value if we do not supply the value
  • A default value of a Optional Argument must be:
    1. a Constant expression
    2. a value type such as enum or struct
    3. an expression of the form default (valueType)
  • It must be set at the end of parameter list

Now consider given below is our function definition with optional arguments.

C#
private static double FindAreaWithOptional(int length, int width=56)
        {
            try
            {
                return (length * width);
            }
            catch (Exception)
            {
                throw new NotImplementedException();
            }
        }

Here, we have set the value for width as optional and gave value as 56. right? Now we will try to call this function.

If you note, the IntelliSense itself shows you the optional argument as shown in the below image:

Image 6

Now, if you call the function as shown in the preceding code block, the function will be fired and give you the same output.

C#
Console.WriteLine("Area with Optional Argument : ");
area = FindAreaWithOptional(120);
Console.WriteLine(area);
Console.Read();

Note that we did not get any error while compiling and it will give you an output as follows:

Image 7

Conclusion

I hope you liked this article. Please share your valuable thoughts and comments. Your feedback is always welcome.

Thanks in advance. Happy coding!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Germany Germany
I am Sibeesh Venu, an engineer by profession and writer by passion. I’m neither an expert nor a guru. I have been awarded Microsoft MVP 3 times, C# Corner MVP 5 times, DZone MVB. I always love to learn new technologies, and I strongly believe that the one who stops learning is old.

My Blog: Sibeesh Passion
My Website: Sibeesh Venu

Comments and Discussions

 
QuestionSome thoughts about my vote of 4 Pin
Klaus Luedenscheidt6-Jul-15 19:06
Klaus Luedenscheidt6-Jul-15 19:06 
AnswerRe: Some thoughts about my vote of 4 Pin
Sibeesh Passion6-Jul-15 19:09
professionalSibeesh Passion6-Jul-15 19:09 
Thank you so much for your feedback. In some cases there may be a situation, where one argument is always fixed right?In our case, it is width which is stable. That is what I meant.
==================!!!====================!!!========================
So much complexity in software comes from trying to make one thing do two things.
Kindest Regards
Sibeesh
http://sibeeshpassion.com/

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.