How to create a function with an optional parameter in C#

1 Answer

0 votes
using System;

class Program
{
    // ------------------------------------------------------------
    // A function with an optional parameter
    // ------------------------------------------------------------
    // The parameter "greeting" is optional because it has a default value.
    // If the caller does not supply it, "Hello" will be used automatically.
    // ------------------------------------------------------------
    static string Greet(string name, string greeting = "Hello") {
        return $"{greeting}, {name}";
    }

    // ------------------------------------------------------------
    // Main program
    // ------------------------------------------------------------
    static void Main()
    {
        // Calling the function WITHOUT the optional parameter
        string result1 = Greet("Happy");

        // Calling the function WITH the optional parameter
        string result2 = Greet("Hippo", "Welcome");

        Console.WriteLine(result1);
        Console.WriteLine(result2);
    }
}


/*
run:

Hello, Happy
Welcome, Hippo

*/

 



answered 4 hours ago by avibootz
...