C# Methods and Parameters
Investigates the details of C# methods and their parameters. Includes passing by value, passing by reference, and returning data via an out parameter.
Save 35% off the list price* of the related book or multi-format eBook (EPUB + MOBI + PDF) with discount code ARTICLE.
* See informit.com/terms
From what you have learned about C# programming so far, you should be able to write straightforward programs consisting of a list of statements, similar to the way programs were created in the 1970s. Programming has come a long way since the 1970s, however; as programs have become more complex, new paradigms have emerged to manage that complexity. Procedural or structured programming provides constructs by which statements are grouped together to form units. Furthermore, with structured programming, it is possible to pass data to a group of statements and then have data returned once the statements have executed.
Besides the basics of calling and defining methods, this chapter covers some slightly more advanced concepts—namely, recursion, method overloading, optional parameters, and named arguments. All method calls discussed so far and through the end of this chapter are static (a concept that Chapter 6 explores in detail).
Even as early as the HelloWorld program in Chapter 1, you learned how to define a method. In that example, you defined the Main() method. In this chapter, you will learn about method creation in more detail, including the special C# syntaxes (ref and out) for parameters that pass variables rather than values to methods. Lastly, we will touch on some rudimentary error handling.
Calling a Method
A method is always associated with a type—usually a class—that provides a means of grouping related methods together.
Methods can receive data via arguments that are supplied for their parameters. Parameters are variables used for passing data from the caller (the code containing the method call) to the invoked method (Write(), WriteLine(), GetFiles(), CountLines(), and so on). In Listing 5.1, files and lineCount are examples of arguments passed to the CountLines() and DisplayLineCount() methods via their parameters. Methods can also return data to the caller via a return value (in Listing 5.1, the GetFiles() method call has a return value that is assigned to files).
To begin, we reexamine System.Console.Write(), System.Console.WriteLine(), and System.Console.ReadLine() from Chapter 1. This time we look at them as examples of method calls in general instead of looking at the specifics of printing and retrieving data from the console. Listing 5.2 shows each of the three methods in use.
Listing 5.2: A Simple Method Call
class HeyYou { static void Main() { string firstName; string lastName; System.Console.WriteLine("Hey you!"); System.Console.Write("Enter your first name: "); firstName = System.Console.ReadLine(); System.Console.Write("Enter your last name: "); lastName = System.Console.ReadLine(); System.Console.WriteLine( $"Your full name is { firstName } { lastName }."); } }
The parts of the method call include the method name, argument list, and returned value. A fully qualified method name includes a namespace, type name, and method name; a period separates each part of a fully qualified method name. As we will see, methods are often called with only a part of their fully qualified name.
Namespaces
Namespaces are a categorization mechanism for grouping all types related to a particular area of functionality. Namespaces are hierarchical and can have arbitrarily many levels in the hierarchy, though namespaces with more than half a dozen levels are rare. Typically the hierarchy begins with a company name, and then a product name, and then the functional area. For example, in Microsoft.Win32.Networking, the outermost namespace is Microsoft, which contains an inner namespace Win32, which in turn contains an even more deeply nested Networking namespace.
Namespaces are primarily used to organize types by area of functionality so that they can be more easily found and understood. However, they can also be used to avoid type name collisions. For example, the compiler can distinguish between two types with the name Button as long as each type has a different namespace. Thus you can disambiguate types System.Web.UI.WebControls.Button and System.Windows.Controls.Button.
In Listing 5.2, the Console type is found within the System namespace. The System namespace contains the types that enable the programmer to perform many fundamental programming activities. Almost all C# programs use types within the System namespace. Table 5.1 provides a listing of other common namespaces.
Table 5.1: Common Namespaces
Namespace |
Description |
System |
Contains the fundamental types and types for conversion between types, mathematics, program invocation, and environment management. |
System.Collections.Generics |
Contains strongly typed collections that use generics. |
System.Data |
Contains types used for working with databases. |
System.Drawing |
Contains types for drawing to the display device and working with images. |
System.IO |
Contains types for working with directories and manipulating, loading, and saving files. |
System.Linq |
Contains classes and interfaces for querying data in collections using a Language Integrated Query. |
System.Text |
Contains types for working with strings and various text encodings, and for converting between those encodings. |
System.Text.RegularExpressions |
Contains types for working with regular expressions. |
System.Threading |
Contains types for multithreaded programming. |
System.Threading.Tasks |
Contains types for task-based asynchrony. |
System.Web |
Contains types that enable browser-to-server communication, generally over HTTP. The functionality within this namespace is used to support ASP.NET. |
System.Windows |
Contains types for creating rich user interfaces starting with .NET 3.0 using a UI technology called Windows Presentation Framework (WPF) that leverages Extensible Application Markup Language (XAML) for declarative design of the UI. |
System.Xml |
Contains standards-based support for XML processing. |
|
It is not always necessary to provide the namespace when calling a method. For example, if the call expression appears in a type in the same namespace as the called method, the compiler can infer the namespace to be the namespace that contains the type. Later in this chapter, you will see how the using directive eliminates the need for a namespace qualifier as well.
Type Name
Calls to static methods require the type name qualifier as long as the target method is not within the same type.1 (As discussed later in the chapter, a using static directive allows you to omit the type name.) For example, a call expression of Console.WriteLine() found in the method HelloWorld.Main() requires the type, Console, to be specified. However, just as with the namespace, C# allows the omission of the type name from a method call whenever the method is a member of the type containing the call expression. (Examples of method calls such as this appear in Listing 5.4.) The type name is unnecessary in such cases because the compiler infers the type from the location of the call. If the compiler can make no such inference, the name must be provided as part of the method call.
At their core, types are a means of grouping together methods and their associated data. For example, Console is the type that contains the Write(), WriteLine(), and ReadLine() methods (among others). All of these methods are in the same group because they belong to the Console type.
Scope
In Chapter 4, you learned that the scope of a program element is the region of text in which it can be referred to by its unqualified name. A call that appears inside a type declaration to a method declared in that type does not require the type qualifier because the method is in scope throughout its containing type. Similarly, a type is in scope throughout the namespace that declares it; therefore, a method call that appears in a type in a particular namespace need not specify that namespace in the method call name.
Method Name
Every method call contains a method name, which might or might not be qualified with a namespace and type name, as we have discussed. After the method name comes the argument list, which is a parenthesized, comma-separated list of the values that correspond to the parameters of the method.
Parameters and Arguments
A method can take any number of parameters, and each parameter is of a specific data type. The values that the caller supplies for parameters are called the arguments; every argument must correspond to a particular parameter. For example, the following method call has three arguments:
System.IO.File.Copy( oldFileName, newFileName, false)
The method is found on the class File, which is located in the namespace System.IO. It is declared to have three parameters, with the first and second being of type string and the third being of type bool. In this example, we use variables (oldFileName and newFileName) of type string for the old and new filenames, and then specify false to indicate that the copy should fail if the new filename already exists.
Method Return Values
In contrast to System.Console.WriteLine(), the method call System.Console.ReadLine() in Listing 5.2 does not have any arguments because the method is declared to take no parameters. However, this method happens to have a method return value. The method return value is a means of transferring results from a called method back to the caller. Because System.Console.ReadLine() has a return value, it is possible to assign the return value to the variable firstName. In addition, it is possible to pass this method return value itself as an argument to another method call, as shown in Listing 5.3.
Listing 5.3: Passing a Method Return Value as an Argument to Another Method Call
class Program { static void Main() { System.Console.Write("Enter your first name: "); System.Console.WriteLine("Hello {0}!", System.Console.ReadLine()); } }
Instead of assigning the returned value to a variable and then using that variable as an argument to the call to System.Console.WriteLine(), Listing 5.3 calls the System.Console.ReadLine() method within the call to System.Console.WriteLine(). At execution time, the System.Console.ReadLine() method executes first, and its return value is passed directly into the System.Console.WriteLine() method, rather than into a variable.
Not all methods return data. Both versions of System.Console.Write() and System.Console.WriteLine() are examples of such methods. As you will see shortly, these methods specify a return type of void, just as the HelloWorld declaration of Main returned void.
Statement versus Method Call
Listing 5.3 provides a demonstration of the difference between a statement and a method call. Although System.Console.WriteLine("Hello {0}!", System.Console.ReadLine()); is a single statement, it contains two method calls. A statement often contains one or more expressions, and in this example, two of those expressions are method calls. Therefore, method calls form parts of statements.
Although coding multiple method calls in a single statement often reduces the amount of code, it does not necessarily increase the readability and seldom offers a significant performance advantage. Developers should favor readability over brevity.