C # Tutorial Lesson Five: Methods

Source: Internet
Author: User
Tags foreach continue instance method modifier modifiers readline reference valid
Tutorial This lesson introduces you to C # 's methods, which are designed to:
1. Understanding the structural format of the method

2. Understand the difference between static and instance methods

3. Learn how to use instance objects

4. Learn how to invoke instantiated objects

5. Use of the four parameter types of the learning method

6. Learn to use "this" reference

In the past, for each program, all work was done in the main () method. This is appropriate for a simple, functional program because it is only used to learn some concepts. There is a better way to organize your program, and that is to use the method. method is useful because it allows you to design your logical modules separately in different units.

The structured format of the method is as follows:

Property modifier Returns the value type method name (parameter) {statement}

We'll discuss the attributes and modifiers in the course that follows. The return value of a method can be any type of C # that can be assigned to a variable to be used later in the program. The method name is unique and can be invoked by the program. To make your code easier to understand and remember, the name of the method can be associated with the operation to be performed. You can either pass the data to the method or return the data from the method. They are surrounded by curly braces. The statement in curly braces implements the functionality of the method.

1. Listing 5-1. An easy way: OneMethod.cs

Using System;
Class Onemethod {
public static void Main () {
String MyChoice;
Onemethod om = new Onemethod ();

do {
MyChoice = Om.getchoice ();
Make a decision based on the user ' s choice
Switch (mychoice) {
Case "A":
Case "a":
Console.WriteLine ("You wish to add");
Break
Case "D":
Case "D":
Console.WriteLine ("You wish to delete");
Break
Case "M":
Case "M":
Console.WriteLine ("You wish to modify");
Break
Case "V":
Case "V":
Console.WriteLine ("You are wish to view the address list.");
Break
Case "Q":
Case "Q":
Console.WriteLine ("Bye.");
Break
Default
Console.WriteLine ("{0} is not a valid choice", mychoice);
}

Pause to allow the user to the results
Console.Write ("Press any key to continue ...");
Console.ReadLine ();
Console.WriteLine ();
while (MyChoice!= "q" && mychoice!= "Q"); Keep going until the user wants to quit
}

String Getchoice () {
String MyChoice;
Print A Menu
Console.WriteLine ("My Address book\n");
Console.WriteLine ("A-add New address");
Console.WriteLine ("D-delete address");
Console.WriteLine ("M-modify address");
Console.WriteLine ("V-view Addresses");
Console.WriteLine ("q-quit\n");
Console.WriteLine ("Choice (A,d,m,v,or Q):");

Retrieve the user ' s choice
MyChoice = Console.ReadLine ();
return mychoice;
}
}

Description

1. The procedure in listing 5-1 is similar to the Doloop procedure in lesson fourth.

The difference is that the program in the previous lesson prints out the menu content and accepts the user's input in the main () method, which in this lesson is implemented with a method named Getchoice (), and the return value type of the method is a string type. In the main method, the string is used in the switch statement. Method "Getchoice" implements the work that is done when the call is made. The parentheses behind the method name are empty, because no data is required to be passed when the Getchoice () method is invoked.

2. In the method block, we first define the variable "MyChoice".

Although it is the same type as the "mychoice" variable in the Main () method, it is a different two variable because the local variable is visible only within the block that it defines. In other words, the "MyChoice" in the Getchoice () method does not have the slightest connection to the "mychoice" variable in the main () method. The Getchoice () method prints out a menu to the console and reads the user's input. The return statement returns the "MyChoice" variable value to the caller Getchoice () in the main () method. Note: The return statement returns a type that is the same as the return value type defined in the method, in this case, the return value is a string.

3. In the main () method, a new "Onemethod" object was instantiated before the Getchoice () was used.

This is because: we do not specify a "static" modifier. (Note: the Main () function has a "static" modifier), and Getchoice () is the method of an instance. The difference between an instance method and a static method is that the former can create instances of multiple classes, each with its own separate Getchoice () method. And once the method is static, there is no instance of the method, you can only invoke one implementation of the static method.

So, as we said earlier, because Getchoice () is not static, we have to instantiate a new object to use it. This is done by defining "Onemethod om = new Onemethod ()". On the left side of the equal sign is the object reference "Om", which is of type Onemethod. "Om" is a reference to an object, and it is important that "OM" is not the object itself, it is a variable referencing the Onemethod type object. On the right side of the equal sign, assign the newly created Onemethod object to the reference "Om". The keyword "new" is a C # operator that creates a new instance of an object on the heap. The work done here is to create a new Onemethod instance on the heap and assign it to an OM reference. Once you have an instance of the Onemethod object that the OM references, you can use an OM primer to process the instance.

Methods, fields, and other class members can pass the "." (dot) operator to access, identify, and manipulate. Once you need to invoke the method Getchoice (), you pass the OM reference and use the dot operator "Om.getchoice ()". The statement in the Getchoice () block is returned after execution completes. To capture the return value of the Getchoice (), we used the assignment operator "=". The return string is placed in the local variable mychoice of the main () function, from where the rest of the program executes as described in the previous course.

2. Listing 5-2. Method Parameters: MethodParams.cs

Using System;
Class Address {
public string name;
public string address;
}
Class Methodparams {

public static void Main () {
String MyChoice;
Methodparams MP = new Methodparams ();
do {
Show menu and get input from user
MyChoice = Mp.getchoice ();
Make a decision based on the user ' s choice
Mp.makedecision (MyChoice);
Pause to allow the user to the results
Console.Write ("Press any key to continue ...");
Console.ReadLine ();
Console.WriteLine ();
while (MyChoice!= "q" && mychoice!= "Q"); Keep going until the user wants to quit
}

Show menu and get user ' s choice
String Getchoice () {
String MyChoice;
Print A Menu
Console.WriteLine ("My Address book\n");
Console.WriteLine ("A-add New address");
Console.WriteLine ("D-delete address");
Console.WriteLine ("M-modify address");
Console.WriteLine ("V-view Addresses");
Console.WriteLine ("q-quit\n");
Console.WriteLine ("Choice (A,d,m,v,or Q):");
Retrieve the user ' s choice
MyChoice = Console.ReadLine ();
return mychoice;
}

Make decision
void Makedecision (String mychoice) {
Address addr = new address ();
Switch (mychoice) {
Case "A":
Case "a":
Addr.name = "Joe";
Addr.address = "C # station";
This.addaddress (ref addr);
Break
Case "D":
Case "D":
Addr.name = "Robert";
This.deleteaddress (Addr.name);
Break
Case "M":
Case "M":
Addr.name = "Matt";
This.modifyaddress (out addr);
Console.WriteLine ("Name is now {0}.", Addr.name);
Break
Case "V":
Case "V":
This.viewaddresses ("Cheryl", "Joe", "Matt", "Robert");
Break
Case "Q":
Case "Q":
Console.WriteLine ("Bye.");
Break
Default
Console.WriteLine ("{0} is not a valid choice", mychoice);
}
}

Insert an Address
void addaddress (ref address addr) {
Console.WriteLine ("Name: {0}, Address: {1} added.", Addr.name, addr.address);
}
Remove an address
void Deleteaddress (string name) {
Console.WriteLine ("You wish to delete {0} ',", name);
}
Change a address
void modifyaddress (out address addr) {
Console.WriteLine ("Name: {0}.", Addr.name); Causes error!
addr = new address ();
Addr.name = "Joe";
Addr.address = "C # station";
}
Show addresses
void viewaddresses (params string[] names) {
foreach (string name in names) {
Console.WriteLine ("Name: {0}", name);
}
}
}

Description

1. Listing 5-2 is a revision of listing 5-1, which is primarily modular for the program and adds more implementations to illustrate the use of parameter passing.

C # can handle four types of parameters: Out (output), ref (Reference), params (array) and value (values). To illustrate the use of parameters, we create an address class with two string fields.

2. In the main () method, we call Getchoice () to read the user's input and place the string in the MyChoice variable.

After that, the MyChoice variable is taken as the real parameter of the makedecision () function. When implementing the Makedecision () method, note that its formal arguments are string mychoice. Again, this is a new mychoice variable, different from the caller's actual argument, just the local variable that applies to this method. Because the MyChoice parameter of the Makedecision () method does not have any other modifiers, therefore, it is regarded as the "value" parameter, that is, the value of the actual parameter is copied to the stack, so the variable as the value parameter is local, any change to the value of the local variable does not affect the value of the caller's real parameter. In other words, the value parameter is only input from the caller.

The switch statement in the 3.makeDecision () method completes the following functions:

In each case, the corresponding method is called. The invocation of these methods differs from the main () method. In addition to using the "MP" reference, they also use the "this" keyword. "This" is a reference to the current object. Because the Makedecision () method is not a static method and the current object is already instantiated, you can use the "this" reference to invoke the method in the same instance.

The 4.addAddress () method uses the "ref" parameter, which means that the reference can be passed as a parameter, that is, the reference is copied to the stack, and its referenced object is the same as the object referenced by the caller's argument.

This means that any change to a locally referenced object is a change to the object referenced by the caller. As you can imagine, this is equivalent to an input/output parameter.

There is an output parameter in 5.modifyAddress ().

The output parameter is passed only to the called function. Once this method is invoked, the only reference in the stack is not assigned, because the variable cannot be used until the variable has not been assigned, based on the deterministic principle of the assignment. This is illustrated by the first line of the Modifyaddress () method as a comment. You can try to remove the annotation, compile the program, and see what happens. Once the variable is assigned a value, the output parameter is copied to the caller's argument after the program returns. Therefore, you must assign a value to an output parameter before the method returns.

Summary
A useful parameter type for the C # language is an array parameter, which must be a one-dimensional or multidimensional array. In the Makedecision () method, we passed a string argument separated by four commas. The number of arguments is a variable. In the Viewaddresses () method, a Foreach loop is used to output the strings individually. The array parameter is only an input parameter, and any change in the value of the logarithmic group parameter only affects the local replica value.

In a nutshell, you have now understood the organizational structure of the method. You also know the four types of parameters and their formats that can be used to implement the method. Once you use an instance method, you must instantiate the object, the static method is different, and the latter can be invoked at any time. In addition, you also know how the "this" reference invokes the instance method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.