Introduction: Optional Arguments In C#

In this post, we will learn about Optional Arguments In C#. An optional parameter has a default value.

Description:

In my previous posts I have explained various topics likeĀ difference between Stack and Heap memory in C#, Difference Between Class And Structure, ASP.NET Core, C# static constructor, Nullables in C# Collections in C#SortedSet in C#.Net,Stack in C#,Queue in C#.Net,LinkedList in C#.Net.



Now in this post, I will explain aboutĀ Optional Arguments In C# with appropriate example.By using this new feature in C#.Net , we can add default values for formal parameters.There can be any number of Optional Arguments in a method.Optional Arguments are defined at the end of the parameter list in method.

Example:

Create Console Application in Visual Studio and write below lines of codes in it.

using System;
using System.Collections;

namespace ConsoleDemo
{   
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("DotNetK.Com");

            ///Call the method by omiting Optional Arguments  
            Program.GetDetails(1, "Raj");

            ///Call the method by omiting 'course' Optional Arguments  
            Program.GetDetails(2, "Mahesh", 11);

            ///Call the method with all the parameters that will override the default values  
            Program.GetDetails(3, "Pinak", 12, "Science");
            Console.ReadLine();  
        }

        public static void GetDetails(int roll_No, string name, int id = 10, string course = "Btech")
        {
            Console.WriteLine(string.Format("Roll No.: {0}, Name: {1}, id: {2}, Course: {3}", roll_No, name, id, course));
        }
    }   
}

Optional Arguments In C#

Optional Arguments In C#

I hope you got an idea about Optional Arguments In C#.
I would like to have feedback from my blog readers.
I hope after reading this article you will be able to do this.
Your valuable feedback, question, or comments about this article are always welcome.

Leave a Reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website