Yesterday I wrote a program about socket receiving udp packets and called socket. the ReceiveFrom method finds a question about ref and out parameter transfer in c #. Here we will discuss it with you. First, we declare that the following conclusions are my speculation, we have not yet reached any conclusion. please correct me if you have any errors.
First, the prototype of the ReceiveFrom method is
Public int ReceiveFrom (byte [], ref EndPoint );
There is an EndPoint parameter for ref, which is used to return the source address information of the received package. The syntax of ref is to transmit the reference, that is, the modification to the passed reference can be reflected outside the method. I usually use IPEndPoint to indicate the address information, so the following call method is naturally used.
(Code 1)
IPEndPoint iep = new IPEndPoint (IPAddress. Any, 0 );
Socket. ReceiveFrom (buffer, ref (EndPoint) iep );
At this time, the following error occurs during compilation. "The ref or out parameter must be an lvalue". How is iep not a left value? The key is the forced conversion (such as (EndPoint) iep) used to call the method. I changed the code
(Code 2)
IPEndPoint iep = new IPEndPoint (IPAddress. Any, 0 );
EndPoint ep = (EndPoint) iep;
Socket. ReceiveFrom (buffer, ref (EndPoint) iep );
This time compiled. Why is there a problem during method calling? Here we need to consider the details of type forced conversion. During forced conversion, the compiler will generate a temporary reference and then pass this temporary reference to a reference of the same type as the conversion, this temporary reference is special-it is not a left value (lvalue) and cannot be assigned a value! The method for using the ref parameter generally needs to modify this reference. If the temporary reference is directly passed in, the compiler will complain that the ref or out parameter must be an lvalue. Code 2 first assigns a temporary reference to a regular reference, and then the regular reference can be copied.