I'm not a veteran in socket programming, so while analyzing code I found in a database API I came across this code
public static void WriteInt(int i, NetworkStream bufOutputStream)
{
byte[] buffer = new byte[IntSize];
WriteInt(i, buffer, 0);
bufOutputStream.Write(buffer, 0, buffer.Length);
}
public static void WriteInt(int i, byte[] byte_array, int pos)
{
byte_array[pos] =(byte)( 0xff & (i >> 24)); byte_array[pos+1] = (byte)(0xff & (i >> 16)); byte_array[pos+2] = (byte)(0xff & (i >> 8)); byte_array[pos+3] = (byte)(0xff & i);
}
I understand the bit-shifts what I don't understand is how the 'buffer' var keeps getting a value when no ref is in the args or no return is made. the bitshifts are somehow editing the actual value of buffer?
Passing value objects by reference is in general a bad design. There are certain scenarios it's valid for, like array position swapping for high performance sorting operations. There are very few reasons you should need this functionality. In C# the usage of the OUT keyword is generally a shortcoming in and of itself.
The ref keyword indicates that a variable is a reference, or an alias for another object. It's used in five different contexts: In a method signature and in a method call, to pass an argument to a method by reference.
No. ref keyword is used when a called method has to update the passed parameter. out keyword is used when a called method has to update multiple parameter passed. ref keyword is used to pass data in bi-directional way.
By default, C# does not allow you to choose whether to pass each argument by value or by reference. Value types are passed by value. Objects are not passed to methods; rather, references to objects are passed—the references themselves are passed by value.
Your confusion is a very common one. The essential point is realising that "reference types" and "passing by refrence" (ref
keyboard) are totally independent. In this specific case, since byte[]
is a reference type (as are all arrays), it means the object is not copied when you pass it around, hence you are always referring to the same object.
I strongly recommend that you read Jon Skeet's excellent article on Parameter passing in C#, and all should become clear...
Because an array isn't a value type, it's a reference type. The reference to the location on the heap is passed by value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With