Do local references destruct on method exit?

Z

Zytan

(Sorry, I accidentally posted this to
microsoft.public.dotnet.csharp.general, and I didn't mean to!)

In the following method, a byte array is made, and then passed to
Socket.BeginReceive. The byte array is local. But, presumably,
Socket.BeginReceive creates a reference to it, so the byte array (a
reference) does disappear, but the object the reference 'points' to
(the array data) is referenced by something inside of
Socket.BeginReceive, so all is well when the data receive call back
(DataReceive_CallBack in this case) is called. Right?

public void MyMethod()
{
byte[] bytesArray = new byte[1024];
mySocket.BeginReceive(bytesArray, 0, bytesArray.Length,
SocketFlags.None, DataReceive_CallBack, bytesArray);
}

Zytan
 
M

Mattias Sjögren

But, presumably,
Socket.BeginReceive creates a reference to it, so the byte array (a
reference) does disappear, but the object the reference 'points' to
(the array data) is referenced by something inside of
Socket.BeginReceive, so all is well when the data receive call back
(DataReceive_CallBack in this case) is called. Right?

You're right that you don't have to worry about the array object being
garbage collected as long as it's in use.


Mattias
 
J

Jon Skeet [C# MVP]

Zytan said:
(Sorry, I accidentally posted this to
microsoft.public.dotnet.csharp.general, and I didn't mean to!)

In the following method, a byte array is made, and then passed to
Socket.BeginReceive. The byte array is local. But, presumably,
Socket.BeginReceive creates a reference to it, so the byte array (a
reference) does disappear, but the object the reference 'points' to
(the array data) is referenced by something inside of
Socket.BeginReceive, so all is well when the data receive call back
(DataReceive_CallBack in this case) is called. Right?

No. The byte array doesn't disappear. The variable "bytesArray"
disappears, but the value of that variable was just a reference. The
byte array itself is on the heap, and isn't local at all.
 
Z

Zytan

You're right that you don't have to worry about the array object being
garbage collected as long as it's in use.

Yes, Mattias, thanks. I just tested and confirmed this.

Zytan
 
Z

Zytan

No. The byte array doesn't disappear. The variable "bytesArray"
disappears, but the value of that variable was just a reference. The
byte array itself is on the heap, and isn't local at all.

Hi Jon, yes, exactly. It was your page on parameter passing that
makes it so clear (and also with the addendum with pictures) that
shows why this is the case, but I just had to be sure. I just
finished testing it to be positive.

Thanks

Zytan
 

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