Posts Tagged ‘Optional Parameters’

I beleive most of you know about overloading in oops.Well,to have some optional parameters some time before, we had to rely on overloading itself.But now things have changed & with the introduction of Optional Parameters in C#4.0,it’s going to be really easy. This is how it will look like.
Eg:

public void ExampleMethod(int required, string optionalstr = "default string",int optionalint = 10)

  • Each optional parameter has a default value as part of its definition.
  • If no argument is sent for that parameter, the default value is used. These default values must be constants.
  • Comma-separated gaps in the argument list are not supported.
  • The following call to ExampleMethod causes a compiler error, because an argument is provided for the third parameter but not for the second.

    ExampleMethod(3, ,4);

    However, if you know the name of the third parameter, you can use a named argument to accomplish the task.

    ExampleMethod(3, optionalint: 4);

  • Optional parameters can also be defined at the end of the parameter list, after any required parameters.
  • public void ExampleMethod(int required,int optionalint = 10,string optionalstr = "default string")

  • If the caller provides an argument for any one of a succession of optional parameters, it must provide arguments for all preceding optional parameters.