Method (1)-Parameter passing

Source: Internet
Author: User

Pass by value

A C # function can have only 0 or 1 return values by default, and the input parameters may have any of these. By default, parameters are passed by value, that is, within the method, and no changes are seen outside the method. However, this depends on whether the parameter itself is a value type or a reference type. If it is a value type, then I believe we all know how to change the method inside, outside can not see, because the pass in is a copy of the value. And if the argument itself is a reference type, then a reference is passed in. (That is, passing objects on the stack by value) at this point, if you change the value of a reference type within a method, it is equivalent to changing the object on the heap to which the reference is directed, and naturally all references to objects on that heap are affected.

classProgram {Static voidMain (string[] args) {Rectangle a=NewRectangle"Info",Ten, -); Rectangle b=A; Rectangle C=A; Change (A,999); Console.WriteLine (string. Format ("A:chang is {0} and Kuan is {1}, Info: {2}", A._chang, A._kuan, a._recinfo.infostring)); Console.WriteLine (string. Format ("B:chang is {0} and Kuan is {1}, Info: {2}", B._chang, B._kuan, b._recinfo.infostring)); Console.WriteLine (string. Format ("C:chang is {0} and Kuan is {1}, Info: {2}", C._chang, C._kuan, c._recinfo.infostring));        Console.readkey (); }         Public Static voidChange (Rectangle R,DoubleChang) {R._chang=Chang; //no meaning, the reference type is passed by value and cannot be changed to point to the reference pointerR =NewRectangle"Newinfo",1,1); }    }    classRectangle { PublicShapeinfo _recinfo;  Public Double_chang;  Public Double_kuan;  PublicRectanglestringRecinfo,DoubleChangDoubleKuan) {_recinfo=NewShapeinfo (Recinfo); _chang=Chang; _kuan=Kuan; }    }

In this example, we modified the value of the field Chang for object A by changing the method change, but all of the a,b,c three objects were affected because the pointers to the three objects on the stack all pointed to one place. One of the following sketches may make a little bit more impression on you. When I modify it, I modify the value of the field Chang on the heap, which clearly points to all of his objects. ( This is for a reference type that has a variability, for a reference type that has invariance, or does not have a variability--a string, we cannot modify its value, that is, we do not have to manipulate the value of the space on his heap, we modify it in another way , We can first think about what this means--by the way, if I can't modify you, I can make another space out of it, and then I put the new value in, and then put your pointer to change exponentially to new space, no, this is exactly what happens when the string is modified! )

So the string is a special case, although the string is a reference type, but it has invariance, that is, once the assignment cannot be changed (space on the heap). Each time you change the value of a string, you actually open up a new piece of memory on the heap, store the new value there, and then change the pointer to the reference on the stack to point to the new memory. For example (example Source: http://www.cnblogs.com/zhili/archive/2013/06/11/ParameterPass.html). Therefore, multiple manipulation of strings will have a bad effect on system performance:

    1. Open up a lot of new space, occupy too much space on the heap
    2. will open up new space, and then the pointer points also change. So the old piece of space, recycled it, obviously not, because the old space is also a string type, is a reference type, and the reference type is to wait for the garbage collector to recycle, so 1:30 will not be recycled, which also affects performance

One solution is to use StringBuilder, because it has variability, so the above two problems are gone.

classProgram {Static voidMain (string[] args) {             stringstr ="Old string";            Changestr (str);                    Console.WriteLine (str); }                Private Static voidCHANGESTR (stringoldstr) {Oldstr="New String";        Console.WriteLine (OLDSTR); }}

This is the value pass of the reference type, passing the reference on the stack, and the pointer cannot be changed. So how can you change the pointer direction? That's going to be passed by reference.

Pass by reference (ref keyword)

The default method is passed by value, and if you want to pass by reference, you must use the REF keyword. Let's talk about value types first. If you are passing in a value type in ref, you can foresee that the external value type will also change (this value type has a behavior similar to the reference type). Obviously, if the passed in reference points to null, then the operation inside the method is equivalent to NULL, and the compiler will give nullexception. So the incoming reference must have been initialized with a value. For example, the following example:

Static voidMain (string[] args) {            stringA ="123"; stringb ="ABC"; //This is also an explicit addition to refSwaprefArefb); Console.WriteLine (string. Format ("a= {0}, b={1}", A, b));        Console.readkey (); }        //value types are passed by reference and are not boxed for value types         Public Static voidSwapref stringAref stringb) {stringtemp =A; A=b; b=temp; }

This simple example demonstrates passing two value types by reference, and when the method has finished running, the external two strings have also changed. It is important to note that value types are not boxed when they are passed by reference. The only address is the one that passes in. When you pass a reference type by reference, the address (or pointer) is passed in, and we can manipulate the address, that is, to change the pointer's direction. We can also change the value of a reference type field, just as it does when it is passed by value.

        Static voidMain (string[] args) {Rectangle a=NewRectangle"Info",Ten, -); Rectangle b=A; Rectangle C=A; Change (refa); Console.WriteLine (string. Format ("A:chang is {0} and Kuan is {1}, Info: {2}", A._chang, A._kuan, a._recinfo.infostring)); Console.WriteLine (string. Format ("B:chang is {0} and Kuan is {1}, Info: {2}", B._chang, B._kuan, b._recinfo.infostring)); Console.WriteLine (string. Format ("C:chang is {0} and Kuan is {1}, Info: {2}", C._chang, C._kuan, c._recinfo.infostring));        Console.readkey (); }         Public Static voidChangerefrectangle R) {            //The reference type is passed by reference, changing the pointer to point to a new objectR =NewRectangle"Newinfo",1,1); }

Note that if you do not pass by reference, the inside of the method

R = new Rectangle ("Newinfo", 1, 1);

It doesn't make any sense.

Method (1)-Parameter passing

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.