Passing Reference by value

Source: Internet
Author: User

Today, when checking for bugs, there is a problem, a dictionary<int[],string> data structure, when using key to take its value:

var tempVar = _dic[key];

Crash occurs. Go in and see, found the wrong Ah, key is some ah, what's the matter? Then it is not possible to have a problem with vs. Looked carefully only then discovered, originally uses as the index key, is not in the dictionary keys in the key.

To put it simply, it is dictionary with the key, and the key is: 1 ', 2 ', 3 '. This is of course not found. This raises the question of the thought of reference types and value types.

Wrote a simple program to organize a bit, the code is as follows.

public class Intarrayproperty {public void verifynew (int[] alist)        {alist = new int[] { -1,-1,-1,};            } public void Verifymodify (int[] alist) {alist[0] =-1;            ALIST[1] =-1;        ALIST[2] =-1; } public static void print (int[] arr) {foreach (var item in arr) {Con Sole.            WriteLine (item);        }}///<summary>//9//9//9//-1//-1//1 </summary> public static void solution () {Intarrayproperty it = new Intarrayproper            Ty ();            Int[] arr = {9, 9, 9};            It.verifynew (arr);            Print (arr);            Int[] Brr = {8, 8, 8};            It.verifymodify (BRR);            Print (BRR);        Console.ReadLine (); }    }

Just look at the code is not enough theory, for this phenomenon, I summed up: You cannot change a reference even if it refers to a reference; You can only modify it unless it's modified by ref keyword.

Analysis: The value of a reference type, when passed, is still the value of the reference. When modified by reference, of course there is no problem; But the new object is assigned only to the copy of the reference that was created when the parameter was passed, so it does not affect the original parameter.

Passing Reference by value

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.