Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass by reference without the ref keyword

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?

like image 955
jtzero Avatar asked Jan 20 '10 16:01

jtzero


People also ask

Is pass by reference bad practice?

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.

What is the keyword to pass the arguments by reference?

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.

What is the difference between the call by reference keywords out and ref?

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.

Is everything passed by reference in C#?

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.


2 Answers

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...

like image 186
Noldorin Avatar answered Sep 20 '22 05:09

Noldorin


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.

like image 22
Yuriy Faktorovich Avatar answered Sep 20 '22 05:09

Yuriy Faktorovich