How does the array name in C # change the value of an argument by modifying the parameter's value?

Source: Internet
Author: User

usingSystem;namespaceconsoleapplication1{classProgram {voidFint[] a) {a[0] =1;         //In this way, the value of the argument can be modified, indicating that the value of the element is modified in the original memory by this method } Static voidMain (string[] args) {Program obj=NewProgram (); int[] A =New int[4] {6,7,8,9 };         OBJ.F (a);  for(inti =0;i<a.length; i++) {Console.Write (A[i]+" ");        } console.readline (); }     }}
void f (int[] a)        {            a = new Int[5] {1, 2, 3, 4, 5};         }
OBJ.F (a);
In this case, the value of the parameter can not be modified by fixing the parameter value;
Because the array itself is a reference type, the reference is stored in the stack, and the referenced value is the memory allocated in the heap;
Take this program analysis, the first parameter and the argument all point to the same memory block, but when a = new Int[5] {1, 2, 3, 4, 5}; When this statement is executed, the equivalent of allocating a memory to the parameter in the heap;
It's completely irrelevant at the moment! If you really want to change the value of an argument in this way, you can use this format! As shown below:

void f (ref int[] a)
{a = new Int[5] {1, 2, 3, 4, 5};

}
OBJ.F (ref a);

How does the array name in C # change the value of an argument by modifying the parameter's value?

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.