C # parameter transfer mechanism

Source: Internet
Author: User

The parameter transfer mechanism of the C # method is different from that of the C and C ++ languages. An output transfer mechanism is added, and the other two mechanisms are value transfer and reference transfer.

Summary:

The parameter transfer mechanism of the C # method is as follows:

 

  1. Value Transfer
  2. Reference Transfer
  3. Output Transmission

 

Based on the above description, we will give an example to illustrate the three transfer mechanisms.


Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;

Namespace Method
{
Class Program
{
Public static void ValueMethod (int I) // pass the value
{
I ++;
}
Public static void RefereceMethod (ref int I) // pass the Parameter
{
I ++;
}
Public static void OutMethod (out int I) // pass the output
{
I = 0;
I ++;
}
Static void Main (string [] args)
{
Int I = 0;
ValueMethod (I );
Console. WriteLine ("I =" + I );
Int j = 0;
RefereceMethod (ref j); // you must add a ref parameter here.
Console. WriteLine ("j =" + j );
Int k = 0;
OutMethod (out k );
Console. WriteLine ("k =" + k );
}
}
}

 

When using these three transfer mechanisms, all the issues that need attention are given in the annotations. The output result of the program is:

I = 0

J = 1

K = 1

In C #, if the local variable of the Main function uses the value transfer method, the parameter remains the value before the call after it is called. Both output and reference parameters change the referenced variable values.

 

Let's talk about the transmission of variable length parameters (params) first look at the Code:

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.