C#: 22-Named and Optional Arguments

Optional Arguments

When arguments are given default values, they become optional

constants can be used


 

    class Logger
    {
        //using Named argument requires static constant variable...
        //..... const is static, so its redundant to use static
        //static string DefaultSystemName = "EmployeeTracker";
        const string DefaultSystemName = "EmployeeTracker";

        //priority type & system that throws log msg
        public static void Log(string msg, string system = DefaultSystemName, int priority=1)
        {
            Console.WriteLine("System: {0}, Priority: {1}, Msg: {2}", system , priority, system);
        }
    }


 

Named Arguments

Name arguments can be used in cases where a placeholder is needed for multi-argument methods with optional arguments

public static void Log(string msg, string system = DefaultSystemName, int priority=1)

where msg & priority will be assigned, but system will use default value

Logger.Log("Tracker has started");
Logger.Log("Using msg & priority", priority:0);
Tags