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?
Your confusion is a very common one. The essential point is realising that “reference types” and “passing by refrence” (
refkeyboard) are totally independent. In this specific case, sincebyte[]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…