简体   繁体   中英

Generic Methods that overwrite parameters without reference?

Okay this might be a really stupid quesion but I will risk my rep anyway. I'm pretty new to programming so take it easy will ya ;) So I just got into TCP when I encountered something I dont quite understand. To be specific:

int length = Socket.Receive(MyByteArray);

To my understanding this method returns the length of the data beeing received and writes the recieved data into my byte array. So how does it write into my byte array without me telling it to? After some research I learned that you can use references to do this kind of thing but this method doesn't require "ref MyByteArray" which leaves me puzzled. Is this a different kind of Method or is it what is going on inside the method (duh)?

Thanks in advance you utterly awesome person.

Passing a reference type into a method can sometimes be an unintuitive thing for developers. Consider these two pieces of code (neither of which use the ref keyword):

void Method1(SomeType myObj)
{
    myObj = new SomeType();
}

void Method2(SomeType myObj)
{
    myObj.SomeProperty = 1;
}

The first method has no side effects. The reference type was passed into the method, which for lack of a better term is basically a "pointer" (itself passed by value) to the object in memory. If you set the variable to a new object in memory, the original remains unchanged. There are then two objects in memory. (Though the new one will go away once the method ends, because nothing uses it.)

The second method, however, does have a side-effect. It uses the same reference to the object in memory, but it modifies the object itself. So anything which examines the object after the method is called will see that modification.


Presumably, Socket.Receive() does something similar to the second method above. It uses the reference to modify the object.


To illustrate how the ref keyword would change this:

void Method3(ref SomeType myObj)
{
    myObj = new SomeType();
}

In this scenario, there is also a side-effect. Any code which calls the method and then, afterward, examines the object it sent to the method will then see that the object has been replaced with a new one. In this case there wasn't a second "pointer" to the same location in memory. The method used the actual pointer that the calling code used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM