C # function and function Overloading

Source: Internet
Author: User

C # function and function Overloading
The focus of this chapter:
◆ Function concept
◆ Function syntax
◆ Function call and execution process

4.1 function concepts
In mathematics, we often hear the concepts of functions, such as sine, cosine, tangent, and cotangent functions in trigonometric functions, as long as the corresponding variables are input, the results can be calculated. The format is y = f (x ). X is called an auto-variable, y is called a variable, and f is called a function name.
Today, in the computer field, we also inherit this way of thinking. We encapsulate a piece of frequently-used code, which can be called directly when needed and return results. The format is y = f (x ). X is called a parameter, y is called a return value, and f is called a function name. At the same time, it also illustrates the complementary relationship between computer and mathematics.

4.1.1 concepts of functions
A function is a piece of prepared code. It can accept parameters, process logic, and then return some data. We usually use functions to implement a single function. by organizing and calling multiple functions, we can implement the functions of the entire program. A function is equivalent to breaking down a complex and large program into a single and small program module. So sometimes we turn functions into subprograms.
In c #, there are two types of functions. One is the standard library function provided during the runtime, called the built-in function. This type of function can be directly used without user-defined. For example, console. write (), console. read (), and other functions. When developing the. net platform, Microsoft has compiled the functions that we often need to use during programming in the optimal way and provided them to users in the form of class libraries. You only need to directly call the function according to the name and rules provided by the built-in function.
Another is a user-defined function, called a user-defined function. Although the built-in functions can provide convenience for program design and improve the quality and efficiency of the program, the number of built-in functions is limited and cannot fully meet the special needs of users. Therefore, the c # language allows you to design functions based on the function syntax of the c # language to implement more personalized functions.
Author's experience:
The function section is very important. It can be said that the advantages and disadvantages of a program are embodied in the function. If the function is used properly, it can make the program look organized and easy to understand. If the function is used in a mess or the function is not used, the program will appear messy, not only making others unable to view it, but also easily confused themselves. It can be said that if a program with more than 100 rows does not use a function, the program must be very arrogant (some are absolute, but it is also a fact ).

4.1.2 function syntax
In the previous section, we talked about built-in functions and user-defined functions. The built-in functions can be used smoothly as long as you know the functions and call rules of the functions. The internal implementation of built-in functions is the same as that of user-defined functions. Therefore, as long as we understand user-defined functions, we naturally understand the use of built-in functions. Next we will introduce the syntax of a custom function, or function syntax for short.
A function consists of two parts: the function header and the statement body. The statement body is easy to understand, that is, the internal implementation of the function. The function header consists of the return value type, function name, and parameter table. The format is as follows:
 

Return Value Type Function Name (parameter table)
{
Statement body;
}


The return value type is used to define the type of data returned by a function. It can be a built-in data type or a custom data type mentioned earlier. The return keyword is used in the statement body to return data. If no return value is returned, use the void keyword instead of the specific return value type.
The function name is used to represent the Function Identifier. Therefore, it must be unique in the program and cannot be defined repeatedly. It must also follow the identifier naming rules we mentioned when talking about variables.
The parameter table is used to transmit external data to the statement body. There can be no or multiple parameters. When a function is called, the parameter can be a value type or a reference type. The modification of the value type parameter in the statement body does not affect the value type data outside the function. However, modification to the reference type parameter in the statement body affects the reference type data outside the function.
The statement body can declare local variables and write the logic of code implementation.
We have actually touched on functions before, for example, the console. writeline () function. We don't know what it is internally. We just need to use it. Here is an example:

Using system;
Namespace microsoft. example
{
Public class testfunction
{
Static int add (int a, int B, int c) // defines the add function
{
Return a + B + c; // return Value
}
Static void main (string [] args)
{
Int a = 1; // defines the int type variable.
Int B = 2; // defines the int type variable B
Int c = 3; // defines the int type variable c
Int result = add (a, B, c); // call the add function
Console. writeline ("result:" + result );
}
}
}
  

In the above Code, row 6th defines an add function, where int is its return value type, and add is the function name. This function requires three integers a B c as the parameter table.
The first row is the statement body of the function, which is used to implement the function. Here, three integers are added. Then, use the return keyword to return the result to the statement that calls the function. Note that the type returned by the return keyword must be the same as the return value type before the function name.
The final output result is:
Result: 6
Author's experience:
The name of a function can be learned. The first thing we need to remember is that the name must be meaningful. Looking at the function name, you can see what the function is for and what functions it implements. In c # language, names are generally named in the dynamic object format, rather than the primary object format. For example, the getage () function.

4.1.3 function call and execution process
The previous section describes how to define a function. This section describes how to call a defined function and how to call it.
Function call format:
Function Name (parameter table );
It should be noted that the function name must be the same as the function name defined by the function. This estimation will not be wrong. The same is true for parameter tables. They must be consistent with the function-defined parameter tables, including the type, number, and order. Multiple parameters are separated by commas. A parameter in a parameter table can be a constant, a variable with a value, or an arithmetic expression.
In c #, function calling is divided based on the position in the program. There are three call methods:
1. It is called in the form of a function call statement. When a function call does not require a return value, it can be implemented by adding a semicolon to the function call, that is, the function call is used as an independent statement.
Example: test ();
The test () function call is equivalent to executing a program.
2. function calls appear directly in an expression as an operation object. For example:
K = sin (x) * cos (y );
The value assignment statement contains two function calls. Each function call is an operation object of an expression. Therefore, the function must bring back a definite value to participate in the operation of the expression. This expression is called a function expression.
3. Use the return value of one function call as the real parameter of another function call. For example, k = sin (cos (x ));
Here is an example:

Using system;
Namespace microsoft. example
{
Public class testtransfer
{
Static int add (int a, int B, int c) // defines the add function
{
Int sum; // defines an int variable sum.
Sum = a * (B + c); // calculate
Console. writeline ("a value:" + );
Console. writeline ("B value:" + B );
Console. writeline ("c value:" + c );
Return sum; // return Value
}
Static void main (string [] args)
{
Int j, sum; // defines two int type variables.
Console. write ("Enter j value :");
Int. tryparse (console. readline (), out j );
Sum = add (j, ++ j, ++ j); // call the add function
Console. writeline ("the calculated sum is:" + sum );
Console. write ("Enter j value :");
Int. tryparse (console. readline (), out j );
Sum = add (++ j, ++ j, j); // call the add function
Console. writeline ("the calculated sum is:" + sum );
}
}
}
  

In the above Code, when j = 1 is input and the function add (j, ++ j, ++ j) is called, the value of the expression is calculated from left to right.
When you call a function in add (, 3), function compute returns 1*(2 + 3) = 5.
When j = 1 is input again and the function add (++ j, ++ j, j) is called, the value of the expression is calculated from left to right, equivalent to adding (, 3) function call, function compute returns 2*(3 + 3) = 12.
Note that c # uses the left-to-right calculation order for parameters as expressions. Other languages may be different. For example, the C language uses the computing sequence from right to left.
The final output result is:
Enter the value of j: 1
The value of a is: 1.
The value of B is 2.
The value of c is 3.
The calculated sum is: 5.
Enter the value of j: 1
The value of a is 2.
The value of B is 3.
The value of c is 3.
The calculated sum is: 12.

 

The focus of this chapter:
◆ Concept of function Overloading
◆ Advantages of function Overloading

4.3 function Overloading
Function overload provides great convenience for program development, especially for users of these class libraries-which can be freed from complicated type conversion, you only need to call the method in the most convenient way we think. This section mainly discusses some basic conditions related to the use of overload from the perspective of the syntax of overload.

4.3.1 concept of function Overloading
Function overloading means that multiple function implementations can use one function name at the same time, but the parameter table of the function is different. For example, we can use overload functions to define multiple addition functions to calculate the sum of two numbers. One function implements the sum of two int types, the other implements the sum of two float types, and the other implements the sum of two decimal types. Each implementation corresponds to a function body. These functions have the same name, but their parameter types are different. This is the concept of function overloading.
We just mentioned that when a function is overloaded, multiple functions use the same function name. Then, the c # Language compiler needs to determine which function the user calls, that is, which function is used for implementation. When determining the function implementation, the number and type of function parameters must be distinguished. This means that during function overloading, functions with the same name are required to have different numbers of parameters or different parameter types. Otherwise, the overload cannot be implemented.
The format of function overload is as follows:
  

Void add (int a, int B)
{}
Void add (int a, int B, int c)
{}
Char add (char a, char B, char c)
{}

In the preceding format, three add functions are defined. The first add () function corresponds to the implementation of two int type summation functions, while the last one is add () the function corresponds to the implementation of the three int-type summation functions. The last add () function corresponds to the implementation of the three char-type summation functions, which is the overload of the function.
Here is an example:

Using system;
Namespace microsoft. example
{
Public class testreturnvalue
{
Static int max (int x, int y) // defines the max function of the int version.
{
Int z;
Z = x> y? X: y; // compare the size of x and y.
Return z;
}
Static double max (double x, double y) // defines the max function of the double version.
{
Double z;
Z = x> y? X: y; // compare the size of x and y.
Return z;
}
Static void main (string [] args)
{
Int intx = 50; // defines an int variable.
Int inty = 43; // defines an int variable.
Console. writeline ("compare the two integers:" + intx + ";" + inty );
Int intresult = max (intx, inty); // call the max function of the int version.
Console. writeline ("Result:" + intresult );
Double doublex = 50.5; // defines a double variable.
Double doubley = 43.3; // defines a double variable.
Console. writeline ("compare the two integers:" + doublex + ";" + doubley );
Double doubleresult = max (doublex, doubley); // call the max function of the int version.
Console. writeline ("Result:" + doubleresult );
}
}
}
  

In the above Code, line 6th defines a max function of the int version. This function only receives two int-type parameters and then returns int-type data. In row 12th, we define a double-type max function. This function only receives two double-type parameters and then returns double-type data. These two functions use the max function name, but they can coexist, which is the function overload.
The final output result is:
Compare the values of two integers: 50; 43
Result: 50
Compare the values of two integers: 50.5 and 43.3.
Result: 50.5

4.3.2 advantages of function Overloading
From the above example, we can know that although different loads are multiple independent functions in form, they represent the same function in semantics-to be precise, they perform the same operation. The main purpose of a function to provide multiple Overloading is to facilitate the caller. Specifically, it includes the following advantages:
1. Support for Multiple Data Types
The previous example of the max function illustrates this. We want to provide the function of "getting the maximum value", instead of "getting the absolute value of an integer". Therefore, it is inappropriate to limit the input parameter to an integer. By providing overloading, you do not have to worry about data type conversion. Each overload function processes different data types and reduces memory.
2. Support multiple data provision Methods
This is more extensive and convenient than supporting multiple data types. Int and double types can be directly converted, but in many cases it is not that simple. For example, the xmldocument class provides the load method for loading an xml document. How do I specify this document? If this document has not been opened, it is most convenient to specify its path and file name. If this document has been opened, it may be most convenient to access it through a stream object. For users of class libraries, these may all exist. If xmldocument enforces a method, it will undoubtedly cause inconvenience to users. The best way to do this is to provide a set of reloads:

Xmldocument. load (string)
Xmldocument. load (stream)


Here, there is no type conversion relationship between string and stream, and the extra work of the overload function is not as simple as the previous maximum function. But for function users, their meanings are similar.
3. provide default values for complex parameters to simplify calls
This is also a very common situation. Some functions are very powerful, but the negative impact is that function callers need to consider too many parameter settings. In fact, in most cases, the user only cares about one or two parameters, and the remaining parameters are concentrated on some of the same set values. If you can provide reasonable default values for these advanced features, the workload of function callers will be greatly reduced. For example, the create method of file is used to create a file. It supports many set parameters:
 

Public void create (
String path;
Int buffersize;
Fileoptions;
Filesecurity;
}

With so many parameters, we will be overwhelmed when creating a file for the first time. As we understand it, it is enough to specify the file address. As shown below:
 

Public void create (
String path;
}


In fact, create does provide such a simple version of overload. In most cases, users only need some simple functions, and those complex features are used less frequently. If the caller needs to set so many parameters each time, it obviously adds a lot of unnecessary work. If you provide a simple version overload that provides reasonable default values for these advanced features, you can make the code more concise and orderly. The previous overload function may be implemented in the following way:
 

Public void create (string path)
{
Create (
Path;
0
Fileoptions. none
Null
);
}

It can be clearly seen that, without these overloading to help set the default parameter values, the user needs to write more code to complete a simple operation.

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.