09 Sep

Optional Argument in C# 4.0

This example shows how to use of Optional Argument in C# 4.0.

Each optional parameter has a default value as its part of the definition. If no argument is sent for the optional parameter, default value is being used. Also, default value of the optional parameter must be constant and optional parameter must define at the end of the all required parameter. It can be applied on constructor, method, and indexer.

Usage :

            OptionalArgument("Test", 123);
            OptionalArgument("Test", 123, optionalParam2:"New Default 2");

Sample Method :

        private void OptionalArgument(string requiredParam1, 
                                      int requiredParam2, 
                                      string optionalParam1 = "Default 1", 
                                      string optionalParam2 = "Default 2")
            //do anything