Optional Parameters in .Net 4.0

Posted: December 13, 2010 in .Net4.0
Tags: , , ,

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.

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.
  • Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out /  Change )

    Google photo

    You are commenting using your Google account. Log Out /  Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out /  Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out /  Change )

    Connecting to %s