When you want to create a new chart, you can combine a set of method calls for the Chart helper that will include all the information needed to build the chart. When you combine method calls to create an object in this way, it is called method chaining. Method chaining can make complex calls in your code more readable and more concise. You can only chain methods with certain classes that have been designed to allow method chaining (and Chart is one of those classes). You chain methods by placing each method call after the other and separate each method using a dot (.) operator. You also can pass parameters to the method. Do not add a semicolon after each method call, you only add a single semicolon after the last method call to end the line of code.
In Chapter 7 – Displaying Data in a Chart of the WebMatrix content on www.asp.net , we show you how to create a chart using chained methods and how to create a chart without using chained methods. However, we didn’t specifically call this out in the chapter. Here, we’ll explain chained methods, but first I’ll show an example of creating a chart using regular method calls.
The following code creates a chart and displays the chart in the browser when you run the page. Here, we have four lines of code. Each line of code ends with a semi-colon. However, notice that I format the code to make it more readable by breaking up a line into several parts. Also, I’m setting properties using named parameters.
Just like the above code, the following code also creates a chart and displays it in the browser when you run the page in WebMatrix. However, we only use one line of code (notice that the line of code ends with a semi-colon). It’s a long line and I have divided it up so that it is easier to read.
We could have formatted the same code as one single line. Here’s what that would look like.
Method chaining offers a quick way to call methods of specific objects, such as the Chart helper. Other helpers in WebMatrix that support method chaining include the WebGrid helper and the WebImage helper.
— Erik Reitan & Tim Teebken
Web Platform and Tools Developer Content
This posting is provided "AS IS" with no warranties, and confers no rights.