0

Let's take for example NetworkStream class.

...
byte[] c = new byte[1];
networkstream1.Read(c,0,1);

How does NetworkStream.Read put data into variable c without using some kind of output parameter?

The signature should be:

Stream.Read(out byte[] buffer, int offset, int count);

It must use pointers?

If someone can elaborate on the (underlying) mechanics of this, thanks :)

  • See the marked duplicate and all other similar references, including Q&A on Stack Overflow. The `buffer` parameter is an array, which is a reference type. So passing the value passes a reference to the object. So changes to the object, whether in the method called or elsewhere, are visible to any other code with the same reference. See also https://stackoverflow.com/questions/1696938/c-sharp-objects-by-ref – Peter Duniho Aug 20 '16 at 20:52

1 Answers1

0

You're passing a reference to the array that is going to be filled up by the method, here's an example to show how that that works

public static void FillArrayWithA(char[] arr)
{
    for(var i = 0;i<arr.Length;i++)
    {
        arr[i]='A';
    }
}


public static void Main(string[] args)
{
     var newArr = new char[10];
     FillArrayWithA(newArr);
     Console.WriteLine(new string(newArr));
}

out and ref are used to modify the actual passed variable, here is an example where that is happening:

public static void NewArrayWithA(out char[] arr)
{
    arr = new char[10];
    for(var i = 0;i<arr.Length;i++)
    {
        arr[i]='A';
    }
}


public static void Main(string[] args)
{
     char[] newArr;
     FillArrayWithA(out newArr);
     Console.WriteLine(new string(newArr));
}

Unlike in the first example the value held in the variable newArr is being assigned a variable by the NewArrayWithA method, the FillArrayWithA method just modifies the array through the reference passed when the method is called

konkked
  • 3,161
  • 14
  • 19