Default Parameters in Lambda Expressions in C#

Default Parameters in Lambda Expressions in C#

In this article, I will discuss Default Parameters in Lambda Expressions in C# with Examples. Please read our previous article discussing the InlineArray Attribute in C# with Examples. In C# 12, a new feature has been introduced that allows you to use default parameters in lambda expressions. This enhancement simplifies the syntax of lambda expressions by enabling default values for parameters, just like in regular methods, providing more flexibility and conciseness when writing functional code.

What’s New in C# 12 Related to Default Parameters in Lambda Expressions?

In C# 12, lambda expressions now support default parameter values. Previously, lambda expressions only allowed you to define parameters without default values. If you wanted a lambda to have optional parameters, you either had to overload the lambda or handle the defaulting logic inside the body. This often resulted in more complex and verbose code.

Before C# 12:

Before C# 12, you had to manually manage default values in the lambda body or use overloaded lambdas. In older versions, we had to manually provide a default value for the parameter since you couldn’t specify it directly in the lambda signature.

namespace CSharp12NewFeatures
{
    public class Program
    {
        static void Main()
        {
            // Lambda with manual default parameter handling
            var logMessage = (string message, bool isError) =>
            {
                // Manually check for the default value of 'isError'
                string logLevel = isError ? "[ERROR]" : "[INFO]";
                Console.WriteLine($"{logLevel} {message}");
            };

            // Call lambda with custom log level
            logMessage("This is an info message.", false);  // Custom: [INFO]
            logMessage("This is an error message.", true);  // Custom: [ERROR]

            // Default handling for optional parameter is manual
            var greet = (string name, string greeting) =>
            {
                greeting = string.IsNullOrEmpty(greeting) ? "Hello" : greeting;
                Console.WriteLine($"{greeting}, {name}!");
            };

            greet("John", "Good morning");
            greet("Jane", "");  // Defaults to "Hello"
        }
    }
}

In this example:

  • The logMessage lambda manually handles isError without default parameters.
  • The greet lambda provides a manual check for the greeting parameter if it’s not provided.
After C# 12:

With C# 12, you can define default parameters in the lambda signature directly. This makes the code cleaner and removes the need for manual checks. The following example shows how default parameters work directly in the lambda expression.

namespace CSharp12NewFeatures
{
    public class Program
    {
        static void Main()
        {
            // Lambda with a default parameter value for 'isError'
            var logMessage = (string message, bool isError = false) =>
            {
                string logLevel = isError ? "[ERROR]" : "[INFO]";
                Console.WriteLine($"{logLevel} {message}");
            };

            // Using default value for 'isError' (false)
            logMessage("This is an info message.");  // Defaults to [INFO]

            // Custom value for 'isError' (true)
            logMessage("This is an error message.", true);  // Custom: [ERROR]

            // Lambda with default parameter for 'greeting'
            var greet = (string name, string greeting = "Hello") =>
            {
                Console.WriteLine($"{greeting}, {name}!");
            };

            // Using default greeting
            greet("John");  // Defaults to "Hello"

            // Providing a custom greeting
            greet("Jane", "Good morning");  // Custom: "Good morning"
        }
    }
}
Code Explanation:
  • logMessage Lambda: The isError parameter has a default value of false. If isError is not provided when the lambda is called, it defaults to false, logging the message as an info message. When isError is provided as true, the message is logged as an error.
  • greet Lambda: The greeting parameter has a default value of “Hello”. If no greeting is provided, it defaults to “Hello”. When a custom greeting (e.g., “Good morning”) is provided, it overrides the default.
Key Points to Remember:
  • Default Parameters in Lambda Expressions (C# 12) simplify optional parameters by allowing you to specify default values directly in the lambda’s signature.
  • Cleaner Code: Before C# 12, you had to manually check for default values inside the body of the lambda. Now, you can specify the default directly in the lambda declaration.
  • Flexibility: You can still override default values when calling the lambda, which provides great flexibility without needing to overload lambdas or manually check values.
Real-Time Example: Task Management System

Task Management System with Default Parameters in Lambda Expressions. The following example will be based on a task management system where we can assign priority levels to tasks. If the priority is not specified, it defaults to “Normal”.

namespace CSharp13NewFeatures
{
    public class Program
    {
        static void Main()
        {
            // Lambda with default parameter for 'priority' (defaults to "Normal")
            var logTask = (string task, string priority = "Normal") =>
            {
                string prefix = priority switch
                {
                    "High" => "[HIGH PRIORITY]",
                    "Low" => "[LOW PRIORITY]",
                    _ => "[NORMAL PRIORITY]"
                };

                Console.WriteLine($"{prefix} - {task}");
            };

            // Logging tasks with different priorities
            logTask("Complete project documentation.");  // Default priority: "Normal"
            logTask("Fix critical bug in the system.", "High");  // Custom priority: "High"
            logTask("Routine system check.", "Low");  // Custom priority: "Low"

            // Demonstrating default behavior
            logTask("Prepare weekly report.");  // Default priority: "Normal"
        }
    }
}
Output:

Default Parameters in Lambda Expressions in C#

Real-Time Example: Sales Reporting System

This example will simulate a sales reporting system where you can calculate and log sales data. The report includes the total sales, the discount applied, and a sales status (defaulting to “Completed”). This example uses default parameters to simplify handling optional parameters in the logging process.

namespace CSharp12NewFeatures
{
    public class Program
    {
        static void Main()
        {
            // Lambda to log sales report with default parameter for sales status
            var logSalesReport = (string product, decimal price, int quantity, decimal discount = 0, string salesStatus = "Completed") =>
            {
                decimal totalPrice = price * quantity;       // Calculate total price
                decimal discountedPrice = totalPrice - discount; // Calculate price after discount

                // Log the sales report with a prefix for the sales status
                string report = $"{salesStatus} - Product: {product}, Quantity: {quantity}, Price: {price}, " +
                                $"Total Price: {totalPrice}, Discount: {discount}, Discounted Price: {discountedPrice}";

                // Display the sales report
                Console.WriteLine(report);
            };

            // Sample sales data (product name, price per unit, quantity sold, optional discount, optional sales status)
            logSalesReport("Laptop", 1000, 5);  // Uses default discount and status (Completed)
            logSalesReport("Smartphone", 500, 10, 50);  // Uses default status (Completed) but custom discount
            logSalesReport("Tablet", 300, 15, 100, "Returned");  // Custom status and discount
            logSalesReport("Headphones", 150, 8, 20, "In Progress"); // Custom status and discount
        }
    }
}
Output:

Default Parameters in Lambda Expressions in C# with Examples

The ability to use default parameters in lambda expressions introduced in C# 12 enhances code readability and maintainability. It allows you to declare optional parameters with default values directly in the lambda expression, eliminating the need for manual checks or overloaded methods. This makes lambda expressions much more concise and flexible, especially in situations where parameters can be optionally omitted.

In the next article, I will discuss Ref Readonly Parameters in C# with Examples. In this article, I explain Default Parameters in Lambda Expressions in C# with Examples. I want your feedback. Please post your feedback, questions, or comments about this article.

Leave a Reply

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