Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Optional Parameters in C#
3.
Examples
3.1.
Code 1
3.2.
Code 2
3.3.
Code 3
4.
Optional Parameters Overview
5.
Frequently Asked Questions
5.1.
What is the use of optional parameters in a method?
5.2.
What happens if we do not pass any parameter to optional arguments?
5.3.
What is the default value of the optional parameter?
6.
Conclusion
Last Updated: Mar 27, 2024

Optional Parameters in C#

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

Optional parameters, as their name implies, are not required. This makes it easier for developers to avoid passing arguments for some of the method's parameters.

This is a typical interview question nowadays. In this article, we shall be discussing the optional parameters in C# along with several code examples and an overview of the topic in the following article.

Optional Parameters in C#

Optional parameters were added in C# 4.0 to declare parameters as optional when defining methods, indexers, constructors, and pointers.

In general, we must pass all method parameters when calling the method. If we mark a few method parameters as optional, we can omit them when calling the method because the optional parameters are not required.

If we wish a parameter to be optional, we must set a default value as part of its declaration in methods, indexers, constructors, and delegates.

If no argument is supplied for an optional parameter when calling the method, the default value will be used; otherwise, the value sent for that parameter will be used.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Examples

Let's walkthrough some coding examples to understand how optional parameters are passed and used.

Code 1

using System;
using System.Runtime.InteropServices;
namespace DemoApplication{
   class CSharp{
      static void Main(string[] args){
         OptionalMethodWithDefaultValue(5);
         OptionalMethodWithDefaultValue(5, 10);
         Console.ReadLine();
      }
      public static void OptionalMethodWithDefaultValue(int value1, [Optional]int value2){
         Console.WriteLine($"Sum is {value1 + value2}");
      }
   }
}

Output

Sum is 5
Sum is 15
The [Optional] attribute expresses an optional parameter in this example.

It also is important to note that optional parameters should always be placed at the end of the list of parameters.

Code 2

using System;
namespace DemoApplication{
   class Demo{
      static void Main(string[] args){
         OptionalMethodWithDefaultValue(5);
         OptionalMethodWithDefaultValue(5, 10);
         Console.ReadLine();
      }
      public static void OptionalMethodWithDefaultValue(int value1 = 5, int value2){
         Console.WriteLine($"Sum is {value1 + value2}");
      }
   }
}

Output

Error − Optional Parameters must appear after all required parameters.

In this example, we have not passed the default parameter; hence the error is visible.

Code 3

using System;  
class CSharp {


    static public void scholar(string fname, 
                               string lname,
                               int age = 20,
         string branch = "Computer science")
  
    {
        Console.WriteLine("First name: {0}", fname);
        Console.WriteLine("Last name: {0}", lname);
        Console.WriteLine("Age: {0}", age);
        Console.WriteLine("Branch: {0}", branch);
    }
  
    static public void Main()
    {
  
        scholar("Mohammad", "Saalim");
        scholar("Muti ur", "Rahman", 30);
        scholar("Mohammad ", "Yawar", 37,
           "Electronics and Communication");
    }
}

Output

First name: Mohammad
Last name: Saalim
Age: 20
Branch: Computer science
First name: Muti ur
Last name: Rahman
Age: 30
Branch: Computer science
First name: Mohammad 
Last name: Yawar
Age: 37
Branch: Electronics and Communication

In this example, we have added the first name and last names of a few students along with their branches.

Optional Parameters Overview

The following are the key points to remember when using optional parameters in C#.

  • In c# 4.0, optional parameters were introduced, allowing you to specify parameters as optional when defining methods, indexers, constructors, and delegates.
  • In methods, indexers, constructors, and delegates, we must assign the default value to the parameter as part of its definition to make it optional.
  • If no argument is passed for an optional parameter when calling the method.
  • At the end of the parameter list, we must ensure that the optional parameters are defined after any required parameters.
  • We can also use the.NET OptionalAttribute class parameters in C# to define optional parameters without specifying default values.

Also see, c# interview questions

Frequently Asked Questions

What is the use of optional parameters in a method?

A method with optional parameters does not require passing arguments at call time. We call the method without passing any arguments. In the function definition, the optional parameter has a default value. The default value is used if no optional argument value is passed when calling.

What happens if we do not pass any parameter to optional arguments?

The default value is used if no parameter is passed to the optional arguments. Optional parameters are always listed last in the parameter list. In other words, the optional parameter is the last parameter of the method, function Object() { [native code] }, etc.

What is the default value of the optional parameter?

In the function definition, the optional parameter has a default value. The default value is used if no optional argument value is passed when calling. There are several methods for making a parameter optional. OptionalMethodWithDefaultValue (int value1, int value2 = 10) value2 has a default value of 10.

Also Read About - singleton design pattern in c# 

Recommended Readings: Difference between argument and parameter

Conclusion

In this article, we have discussed the Optional Parameters in C#. We have briefly discussed the topic along with its example and output. We also discussed its overview.

Enhance your skills in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem Design, and more with our Coding Ninjas Studio Guided Path. If you want to sharpen your coding skills to the test, check out the mock test series and enter the contests on Coding Ninjas Studio! If you are just a beginner and want to know what questions big giants like Amazon, Microsoft, Meta and Uber ask, check the problemsinterview experiences, and interview bundle for placement preparations and ace your interviews.

We hope that this article might have helped you in enhancing your knowledge. 

If you enjoyed reading this article, please give it a thumbs up. It will motivate us to write more such articles.

 "Happy Coding!"

Live masterclass