Passing a byte[] by ref, and here I thought I knew what was going on.

D

DaTurk

If I call this method, and pass it a byte[] by ref, and initialize
another byte array, set the original equal to it, and then null the
reference, why is the original byte array not null as well? I thought
passing by reference, your passing the address in memory.

public bool DoSomething(ref byte[] data)
{
byte[] retVal = null;

try
{
retVal = new byte[data.Length];

data = retVal;
}
catch (Exception ex)
{
}
finally
{
retVal = null;
}
}
 
T

Terry Rogers

retVal and data are 2 different references (pointers)
data = retVal sets both to reference the same array (i.e. the pointer
memory addresses are equal), you have 2 pointers to the same object
retVal = null clears the retVal reference, but won't touch the data
reference.

If you set data = null then the array reference passed in would be
null
 
C

Christof Nordiek

Hi DaTurk,

yes, passing by reference is passing an address in memory. The address of a
variable wich stores a reference to an array of byte.

Talking about reference could be misleading in C#. You could better think of
a ref and out parameter as passing a variable not a value.

So data here is a (reference type) variable, wich original belonged to the
caller.
retValue is another (reference type) variable, wich is local to this method

In the first line inside the try block you create a new array of byte and
put a reference to it in the variable retVal
After that you copy this reference to th variable data.
In the finally block you put null into the variable retVal; the variable
data is not effected by this.
 
D

DaTurk

So, let me see if I'm understanding, thanks for the responses by the
way, your not actually passing the address to the data in memory.
Your passing the address, of the pointer to the actual address in
memory, meaning your passing the variable by ref. I get it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top