As we saw earlier, a method is a named
block of code. We wrote a method already—the
Main method that runs when our program starts.
And we used methods provided by the .NET Framework class library, such as
File.ReadAllLines. But we haven’t looked at how
and why you would introduce new methods other than
Main into your own code.
Methods are an essential mechanism for reducing your code’s complexity and enhancing its readability. By putting a section of code into its own method with a carefully chosen name that describes what the method does, you can make it much easier for someone looking at the code to work out what your program is meant to do. Also, methods can help avoid repetition—if you need to do similar work in multiple places, a method can help you reuse code.
In our race car example, there’s a job we may need to do multiple times: reading in numeric values from a file. We did this for timing information, but we’re going to need to do the same with fuel consumption and distance. Rather than writing three almost identical bits of code, we can put the majority of the code into a single method.
The first thing we need to do is declare the method—we need to pick
a name, define the information that comes into the method, and optionally
define the information that comes back out. Let’s call the method
ReadNumbersFromFile, since that’s what it’s going to do. Its input will be a text string containing the filename, and it will return an array of double-precision ...