C# Optional Parameters

In c# 4.0, the optional parameters have been introduced to specify the parameters as optional while defining the methods, indexers, constructors, and delegates.

 

Generally, while calling the method we need to pass all the method parameters. In case, if we specify a few of method parameters as an optional, then we can omit those parameters while calling the method because the optional parameters are not mandatory.

 

If we want to make the parameter as an optional, then we need to assign the default value to that parameter as part of its definition in methodsindexersconstructors, and delegates.

 

While calling the method, if no argument is sent for an optional parameter, then the default value will be used otherwise it will use the value which is sent for that parameter.

 

Following is the example of defining the optional parameters in a method.

 

public void GetDetails(int id, string name, string location = "Hyderabad")

{

// your code

}

If you observe the above method, we made the location parameter as an optional by assigning the default value (Hyderabad). So, while accessing GetDetails() method, if no argument sent for location parameter, then it will consider the default “Hyderabad” value otherwise it will use the value which is sent for that parameter.

 

The defined GetDetails() method can be accessed like as shown below.

 

GetDetails(1,"Suresh");

GetDetails(1,"Suresh", "Chennai");

While defining the optional parameters, we need to make sure that the optional parameters are defined at the end of the parameter list, after any required parameters like as we defined in the above method otherwise we will get the compile-time error like “optional parameters must appear after all required parameters”.

 

Following is the invalid way of defining the optional parameters in a method.

 

public void GetDetails(int id, string location = "Hyderabad", string name)

{

// your code

}

The above method will throw the compile-time error because we defined a required parameter (name) after the optional parameter (location). As per rules, the optional parameters must be defined at the end of the parameter list.

C# Multiple Optional Parameters

In case, if you want to define multiple optional parameters, then the method declaration must be like as shown below.

 

public void GetDetails(int id, string name = "Suresh", string location = "Hyderabad")

{

// your code

}

The defined GetDetails() method can be accessed like as shown below. 

 

GetDetails(1);

GetDetails(1, "Rohini");

GetDetails(1, "Trishi", "Guntur");

While calling the method, if we provide an argument for any of succession optional parameters, then we must need to provide an argument for all the preceding optional parameters and the comma separated gaps in the argument list are not supported.

 

Following is the invalid way of defining the optional parameters in a method.

 

GetDetails(1, , "Guntur");

The above caller method will throw a compile-time error like “Argument missing” because we provided an argument for the third parameter but not for a second.

 

However, if you know the name of the third parameter, then you can use a named argument to send a value like as shown below.

 

GetDetails(1, location: "Guntur");

 This is how we can skip preceding optional parameters by using named arguments in caller methods.

C# Optional Parameters Example

Following is the example of defining the optional parameters during method declaration in c#.

 

using System;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            GetDetails(1);

            GetDetails(1, "Rohini");

            GetDetails(1, "Trishi", "Guntur");

            GetDetails(1, location: "Guntur");

            Console.ReadLine();

        }

        public static void GetDetails(int id, string name = "Suresh", string location = "Hyderabad")

        {

            Console.WriteLine("Id:{0}", id);

            Console.WriteLine("Name:{0}", name);

            Console.WriteLine("Location:{0}", location);

        }

    }

}

If you observe the above example, the GetDetails() method has one required parameter (id) and two optional parameters (name, location).

 

When we execute the above program, we will get the result like as shown below.

 

****Only Required Parameter****

Id:1

Name:Suresh

Location:Hyderabad

 

****Required Parameter & One Optional Parameter****

Id:1

Name:Rohini

Location:Hyderabad

 

****Both Required & Optional Parameters****

Id:1

Name:Trishi

Location:Guntur

 

****Required & Second Optional Parameter****

Id:1

Name:Suresh

Location:Guntur

This is how we can define the optional parameters in methodsindexersconstructors, and delegates based on our requirements.

C# Optional Parameters with OptionalAttribute

In c#, we can also define the optional parameters by using .NET OptionalAttribute class. If we define the optional parameters using OptionalAttribute class, then the optional parameters won’t expect any default values.

 

The OptionalAttribute class is available with System.Runtime.InteropServices namespace. So, we need to import System.Runtime.InteropServices namespace in our application to implement optional parameters.

 

We can define the optional parameters by mentioning the Optional keyword which is surrounded by square brackets in front of the parameters like as shown below.

 

public void GetDetails(int id, [Optional]string name, [Optional]string location)

{

// your code

}

If you observe the above code, we defined one required parameter (id) and two optional parameters (name, location) without specifying any default values by mentioning OptionalAttribute class Optional keyword.

C# Optional Parameters with OptionalAttribute Example

Following is the example of defining the optional parameters using OptionalAttribute class in c#.

 

using System;

using System.Runtime.InteropServices;

 

namespace TutlaneExamples

{

    class Program

    {

        static void Main(string[] args)

        {

            GetDetails(1);

            GetDetails(1, "Rohini");

            GetDetails(1, "Trishi", "Guntur");

            GetDetails(1, location: "Guntur");

            Console.ReadLine();

        }

        public static void GetDetails(int id, [Optional]string name, [Optional]string location)

        {

            Console.WriteLine("Id:{0}", id);

            if (!string.IsNullOrEmpty(name))

            {

                Console.WriteLine("Name:{0}", name);

            }

            if (!string.IsNullOrEmpty(location))

            {

                Console.WriteLine("Location:{0}", location);

            }

        }

    }

}

If you observe the above example, we imported System.Runtime.InteropServices namespace to access OptionalAttribute class to define optional parameters by mentioning Optional keyword.

 

When we execute the above program, we will get the result like as shown below.

 

****Only Required Parameter****

Id:1

 

****Required Parameter & One Optional Parameter****

Id:1

Name:Rohini

 

****Both Required & Optional Parameters****

Id:1

Name:Trishi

Location:Guntur

 

****Required & Second Optional Parameter****

Id:1

Location:Guntur

This is how we can define the optional parameters using OptionalAttribute class in c# based on our requirements.

 

In c#, we can also achieve the optional parameters by using method overloading functionality. Generally, the method overloading functionality will allow us to create multiple methods with the same name but with different parameters.

 

To know more about overloading functionality in c#, check Method Overloading in C#.

C# Optional Parameters Overview

Following are the important points which we need to remember about optional parameters in c#.

 

  • The optional parameters have been introduced in c# 4.0 to specify the parameters as an optional while defining the methodsindexersconstructors, and delegates.
  • To make the parameter as an optional, we need to assign the default value to that parameter as part of its definition in methodsindexersconstructors, and delegates.
  • While calling the method, if no argument is sent for an optional parameter, then the default value will be used.
  • While defining the optional parameters, we need to make sure that the optional parameters are defined at the end of the parameter list, after any required parameters.
  • In c#, we can also define the optional parameters by using .NET OptionalAttribute class parameters without specifying any default values.
 
 
 

Topics Covered