Declaring a Method


This section expands on the explanation of declaring a method (such as Main()) to include any parameter or a return type. Listing 4.4 contains examples of these concepts, and Output 4.1 shows the results.

Listing 4.4. Declaring a Method

 class IntroducingMethods {   static void Main() {   string firstName;   string lastName;   string fullName;   System.Console.WriteLine("Hey you!");   firstName = GetUserInput("Enter your first name: ");   lastName = GetUserInput("Enter your last name: ");   fullName = GetFullName(firstName, lastName);   DisplayGreeting(fullName); } static string GetUserInput(string prompt) {     System.Console.Write(prompt);     return System.Console.ReadLine(); } static string GetFullName(string firstName, string lastName) {     return firstName + " " + lastName; } static void DisplayGreeting(string name) {     System.Console.WriteLine("Your full name is {0}.", name);     return;  } } 

Output 4.1.

 Hey you! Enter your first name: Inigo Enter your last name: Montoya Your full name is Inigo Montoya. 

Four methods are declared in Listing 4.4. From Main() the code calls GetUserInput(), followed by a call to GetFullName(). Both of these methods return a value and take parameters. In addition, the listing calls DisplayGreeting(), which doesn't return any data. No method in C# can exist outside the confines of an enclosing class. Even the Main method examined in Chapter 1 must be within a class.

Language Contrast: C++/Visual BasicGlobal Methods

C# provides no global method support; everything must appear within a class definition. This is why the Main() method was marked as staticthe C# equivalent of a C++ global and Visual Basic module method.


Beginner Topic: Refactoring into Methods

The Main() method that is shown in Listing 4.4 results in the same behavior as does the Main() method that is shown in Listing 1.15, in Chapter 1. Perhaps even more noteworthy is that although both listings are trivial to follow, Listing 4.4 is easier to grasp at a glance by just viewing the Main() method and not worrying about the details of each called method's implementation.

Moving a set of statements into a method instead of leaving them inline within a larger method is a form of refactoring. Refactoring reduces code duplication, because you can call the method from multiple places instead of duplicating the code. Refactoring also increases code readability. As part of the coding process, it is a best practice to continually review your code and look for opportunities to refactor. This involves looking for blocks of code that are difficult to understand at a glance and moving them into a method with a name that clearly defines the code's behavior. This practice is often preferred over commenting a block of code, because the method name serves to describe what the implementation does.


Parameter Declaration

Consider the declaration of the DisplayGreeting() and GetFullName() methods. The text that appears between the parentheses of a method declaration is the parameter list. Each parameter in the parameter list includes the type of the parameter along with the parameter name. A comma separates each parameter in the list.

Behaviorally, parameters are virtually identical to local variables, and the naming convention of parameters follows accordingly. Therefore, parameter names are camel case. Also, it is not possible to declare a local variable with the same name as a parameter of the containing method, because this would create two "local variables" of the same name.

Language Contrast: Visual Basic/C++Default Parameters

Unlike Visual Basic and the C-style predecessors, C# does not allow specification of a default value within the method declaration so that the parameter is optional to the caller. For example, it is not possible to declare a method as follows:

void Method(int i=42){}


Optional parameter type APIs are still possible, but they are implemented via method overloading such that one version of the overloaded method does not include the parameters that are to be optional. In other words, you should define a second method with the same name (overloading it) but without the defaulted parameter. Inside this additional method, the code should assign the default value as part of the method implementation (see the section Method Overloading, later in this chapter).


Method Return Declaration

In addition to GetUserInput() and GetFullName() requiring parameters to be specified, both of these methods also include a method return. You can tell there is a method return because a data type appears immediately before the method name of the method declaration. For both GetUserInput() and GetFullName(), the data type is string. Unlike parameters, only one method return is allowable.

Once a method includes a return data type, and assuming no error occurs, it is necessary to specify a return statement for each code path (or set of statements that may execute consecutively) within the method declaration. A return statement begins with the return keyword followed by the value the method is returning. For example, the GetFullName() method's return statement is return firstName + " " + lastName. The C# compiler makes it imperative that the return type match the type of the data specified following the return keyword.

Return statements can appear in spots other than at the end of a method implementation, as long as all code paths include a return if the method has a return type. For example, an if or switch statement at the beginning of a method implementation could include a return statement within the conditional or case statement; see Listing 4.5 for an example.

Listing 4.5. A return Statement before the End of a Method

 class Program {   static void Main()   {       string command;       //...       switch(command)       {           case "quit":               return;           // ...       }       // ...   } } 

A return statement indicates a jump to the end of the method, so no break is required in a switch statement. Once the execution encounters a return, the method call will end.

If particular code paths include statements following the return, then the compiler will issue a warning that indicates the additional statements will never execute. In spite of the C# allowance for early returns, code is generally more readable if there is a single exit location rather than multiple returns sprinkled through various code paths of the method.

Specifying void as a return type indicates that there is no return from the method. As a result, the method does not support assignment to a variable or use as a parameter. Furthermore, the return statement becomes optional, and when it is specified, there is no value following the return keyword. For example, the return of Main() in Listing 4.4 is void and there is no return statement within the method. However, DisplayGreeting() includes a return statement that is not followed by any returned result.

Language Contrast: C++Header Files

Unlike C++, C# classes never separate the implementation from the declaration. In C# there is no header (.h) file or implementation (.cpp) file. Instead, declaration and implementation always appear together in the same file. In C# 2.0, it is possible to spread a class across multiple files known as partial types. However, even then the declaration of a method and the implementation of that method must remain together. For C# to declare types and methods inline makes a cleaner and more maintainable language.





Essential C# 2.0
Essential C# 2.0
ISBN: 0321150775
EAN: 2147483647
Year: 2007
Pages: 185

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net