How Can You Use Optional Parameters In C#

Introduction

C# allows you to define a method, constructor, indexer, or delegate with parameters that are required or optional. The caller code does not need to pass the value of optional parameters as an argument. When declared, each optional parameter has a default value. If no argument is passed by the caller code, the default value is used.

In this article, learn how to define optional parameters in C# methods and how to call a method with optional arguments.

Some important notes about optional parameters A default value must be a constant expression, an expression of the form new ValType(), or an expression of the form default(ValType).

Optional parameters must be defined at the end of the parameter list after any required parameters.

Define a Method with Optional Parameters

The following code snippet defines a class with some properties and a method, CalculateBookRoyalties. This method calculates author book royalties for the books sold. The input parameters are book price, quantity, and rate. The method has one optional parameter, rate. The default value of the rate is 12. That means when no value is passed as an argument, the default value = 12 will be used.

class Author
{
    // Auto-Initialized properties
    public string Name { get; set; }
    public string Book { get; set; }
    public double Price { get; set; }
    // Calculate author's book royalties
    public double CalculateBookRoyalties(double price, int quantity, short rate = 12)
    {
        return (quantity * price * rate) / 100;
    }
}

Call a method with optional parameters

The following code calls the CalculateBookRoyalties method, with two arguments only. The default value of the rate argument = 12 is used in the calculation.

// Create an Author
Author author = new Author { Name = "Mahesh Chand", Book = "Apress", Price = 49.95 };
// Call a method and do not pass optional argument
double royalty = author.CalculateBookRoyalties(50, 100);

 Example. Here is the complete C# code example.

using System;
namespace OptionalParametersSample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an Author
            Author author = new Author { Name = "Mahesh Chand", Book = "Apress", Price = 49.95 };
            // Call a method and do not pass optional argument
            double royalty = author.CalculateBookRoyalties(50, 100);
            Console.WriteLine($"Author Royalties: $ {royalty}");
            Console.ReadKey();
        }
    }
    class Author
    {
        // Auto-Initialized properties
        public string Name { get; set; }
        public string Book { get; set; }
        public double Price { get; set; }
        // Calculate author's book royalties
        public double CalculateBookRoyalties(double price, int quantity, short rate = 12)
        {
            return (quantity * price * rate) / 100;
        }
    }
}

Note. Both named and optional arguments can be used with methods, indexers, constructors, and delegates.

Output. The output of the above code looks like this.

Optional Parameters In CSharp

Learn more about it here. Named Arguments and Optional Parameters


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.