Named and Optional Parameters in C#

By | June 6, 2010

You may know the Optional and Named Parameters from other programming languages. C# supports this functionality since version 4.0.

In the example below you see how you can define Optional Parameters (see signature of “RegisterUser”) and how you can call this method.

class Program
{
    static void Main(string[] args)
    {
        // normal call
        Program.RegisterUser("fname1", "fname1", true);

        // optional parameters
        Program.RegisterUser("fname2", "fname2");

        // named parameters
        Program.RegisterUser(activate: true, firstname: "fname3", lastname: "fname3");

        // named and optional parameters 
        Program.RegisterUser(lastname: "fname4", firstname: "fname4");

        Console.Read();
    }

    public static void RegisterUser(string firstname, string lastname, 
                                        bool activate = false)
    {
        Console.WriteLine(String.Format("Firstname:{0}, Lastname:{1}, Activate:{2}", 
            firstname, lastname, activate.ToString()));
    }
}