C # basic [07] method [I]

Source: Internet
Author: User

I. Method Structure
1. Concepts of methods
The method in C # Is the statement block declared in the type and is a member of the type function. It can have either a name or no name. A method without a method name is called an anonymous method.
2. Method Structure
The method consists of the method header and method body. The method header specifies the features of a method, including whether the method returns the value, the type of the returned value, the method name, and the parameter list. The method body is a sequence of statements that can be executed by a pair of braces, including local variables, process control structures, method calls, and nested blocks. Shows the method structure.

 

3. method declaration example

The following example declares a public method with no return value, the method name is "sayhello", and no parameters.

1 /// <summary> 2 /// method declaration 3 /// </Summary> 4 Public void sayhello () 5 {6 system. Console. writeline ("Hello world! "); 7}

Ii. Local Variables

1. Local Variables
Local variables are variables declared in the method body. Local variables are often used to save local or temporary computing data. Local variables exist in blocks and nested blocks. Local variables can be declared anywhere in the method body, but they must follow the sequence of "declare first, assign values, and then use.

Syntax for declaring local variables: "type identifier = value;", where type indicates the type of the variable, identifier indicates the name of the variable, and value indicates the initial value assigned to the variable. The following method declares two local variables.

1 /// <summary> 2 /// method declaration 3 /// </Summary> 4 Public void sayhello () 5 {6 // declare two local variables "name" and "Age" 7 string name = "yunshi"; 8 int age = 23; 9 system. console. writeline ("My name is {0}. I'm {1} years old! ", Name, age); 10}

2. Comparison between local variables and class Fields

1). Survival: The instance field starts when the instance is created and ends when the instance is no longer accessed. The local variable starts from its declaration in the block until the execution of the block is complete.

2). Implicit initialization: The instance field is implicitly initialized as the default value of its field type. Local variables are not implicitly initialized. All variables must be initialized before they can be used. Otherwise, an error is returned.

3 ). storage location: all fields of the class are stored in the memory heap, regardless of the value type or reference type. If the local variable is a value type, it is stored in the memory stack, if it is a reference type, the reference is stored in the stack, and the actual data is stored in the heap.

3. type inference and VaR

1). type inference

When we declare local variables, most of the time we write a variable type, the compiler can push it out through the value on the right of the equal sign of the value, which is called type inference. For example, int I = 10; the int type on the Left can be inferred from 10 on the right. Due to type inference, the following var keyword is generated.

2). var keyword

Starting from C #3.0, you can use the new var keyword at the position of the explicit type name at the beginning of the variable declaration, which indicates the type that can be inferred from the right of the initialization statement. The int and VaR values in the following two local variable declaration statements are equivalent.

1 // declare two integer variables I and J2 int I = 10; 3 var J = 100;

VaR keyword usage condition: it can only be used for local variables and cannot be used for fields. It can only be used when the variable declaration statement contains initialization. If only one variable is declared but not initialized, VAR cannot be used; the VaR keyword does not change the strong type property of c #. Once the compiler deduce the type of the variable, the type is fixed.

In C #3.0 and later versions, we recommend that you use the VaR keyword to implicitly type local variables in the following situations to simplify program writing:

①. If the variable type on the right side of the value assignment statement is very obvious, or if the exact type is not important, use a local variable of the implicit type. If the type on the right side of the value assignment statement is unknown, do not use var.

1 var var1 = "this is clearly a string. "; 2 var var2 = 27; 3 // The number and string are connected with the" + "sign, and finally converted to the string 4 var var3 = console. readline () + var1 + var2; 5 console. writeline (var3 );

②. Use the implicit type to determine the type of the cyclic variable in the for and foreach loops.

1 // A. Use the implicit type in the for statement. 2 var syllable = "ha"; 3 var laugh = ""; 4 for (VAR I = 0; I <10; I ++) 5 {6 laugh + = syllable; 7. console. writeline (Laugh); 8} 9 10 // B. use the implicit type in the foreach statement. 11 foreach (var ch in laugh) 12 {13 if (CH = 'H') 14 console. write ("H"); 15 else16 console. write (CH); 17}

3. Local Constants

1. Local Constants

A local constant is a constant declared in the method body. Constants (local constants/member constants) have the following features: constants must be initialized at the same time of declaration; values cannot be changed after declaration.

2. Declaration of local Constants

The local constant is declared using the const keyword. Syntax: "const type identifier = value;" const is not a modifier, but a part of the core declaration. It must be placed before the type, and the rest is the same as the local variable declaration syntax. The following is an example of declaring and reading a local constant value:

1 /// <summary> 2 // display the area of the circle 3 /// </Summary> 4 void displayradius () 5 {6 // declare the local constant 7 const double Pi = 3.1416; 8 9 // declare the local variable 10 int radius = 2; 11 12 // read the values of local variables and local constants 13 double area = radius * PI; 14 15 console. writeline ("radius: {0}, Area: {1}", radius, area); 16}

Iv. method call

1. Use "method name + parameter list" to call the method. The following is a method to call the "show area of circle" method. The parameter is null.

1 static void main (string [] ARGs) 2 {3 program P = new program (); 4 // use "Instance name. method Name "Call instance method 5 p. displayradius (); 6}

2. execution sequence of method calls

1) The execution of the current method is suspended at the call point.

2) Transfer Process Control to the start of the called method.

3) The called method is executed until it is completed (or an exception is thrown ).

4). Control the method to initiate a call.

The following figure shows the call sequence:

5. Method Return Value

1. Return Value Type

The purpose of many method declarations is to return values. Whether a method returns a value or the data type of the returned value is determined by the type of the returned value declared by the method. to return a value, you must declare a specific return type before the method name. If the method does not return a value, the void return type must not be declared. The following example declares a method to return the int value:

1 /// <summary> 2 /// get the current hour 3 /// </Summary> 4 /// <returns> </returns> 5 Int gethour () 6 {7 var dt = new datetime (); 8 return DT. hour; 9}

2. Return Statement

1). Normal Return Statement

In the preceding example, the Return Statement returns the current hour. If the return type of a non-void is declared in the method header, A reutrn statement with a definite value must exist on each path passing through the method in the method body. The syntax of the Return Statement is "Return expression;", where expression is a definite value.

2) Return Statement of the void Method

Originally, the void method does not require a return statement, but we can use a return statement without parameters to exit the method in advance to simplify the program logic. The syntax is "reutrn ;". Note that the return statement contains only one semicolon and is only used in the Void method body. The following is an example:

1 /// <summary> 2 /// exit method 3 in advance based on the conditions /// </Summary> 4 /// <Param name = "MSG"> </param> 5 void test (string MSG) 6 {7 if (MSG = "hello") 8 {9 return; 10} 11 console. writeline ("Hello! "); 12}

 

Related Article

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.