Sdílet prostřednictvím


WebMatrix - Positional and Named Parameters

This post provides details and code examples related to Microsoft WebMatrix (Beta).

The code examples used in the WebMatrix Getting Started guide show you how to call methods using two different techniques. You can either call a method using positional parameters or named parameters. You can also use a combination of both, but in a specific way.

Positional Parameters

When you call a method using positional parameters, you pass the parameters in order as specified in the method declaration. You must include each parameter in order because the parameters are recognized by the order. If you don’t want to pass a value for a particular parameter, you can pass an empty string (“”) or null.

For instance, in the “Saving a Chart as an Image File” section of the Charts chapter, the code uses the following positional parameters to create a new Chart object.

Code Snippet

  1. var chartImage = new Chart(600, 400);

In the above code we first create a new chart. We pass two parameters that are integers (600, 400). These are the required parameters. In Visual Studio’s Object Browser, you can see there are four parameters that are exposed (width, height, template and templatePath).

image

The first two parameters are required. The third and fourth parameters are optional. If you wanted to include a template path using positional parameters, it would look like the following:

Code Snippet

  1. var chartXml = new Chart(600, 400, "", "_ChartFiles/XmlChart.xml");

Notice that the third parameter is an empty string. We need to make sure that each parameter is accounted for by position.

Named Parameters

To call a method using named parameters, you specify the parameter name followed by a colon (:), and then the value. I like named parameters because they are more readable. However, the real advantage is that you can pass the named parameters in any order. You also don’t have to include unused parameters.

Code Snippet

  1. chartXml = new Chart(width: 600,
  2.                      height: 400,
  3.                      templatePath: "_ChartFiles/XmlChart.xml");

Combining Positional and Named Parameters

You can also use both named and positional parameters together. However, you cannot use positional parameters after you have used a named parameter.

The following shows an example of using both named and positional parameters:

Code Snippet

  1. chartXml = new Chart(600, 400, templatePath: "_ChartFiles/XmlChart.xml");

For more information about named and positional parameters in C#, see Named and Optional Arguments (C# Programming Guide). For more information about Visual Studio’s Object Browser, see Understanding WebMatrix Helpers using Visual Studio's Object Browser.

 

 

-- Erik Reitan
ASP.NET and Web Tools Developer Content
This posting is provided "AS IS" with no warranties, and confers no rights.