Consider the following code:
// module level declaration
Socket _client;
void ProcessSocket() {
_client = GetSocketFromSomewhere();
using (_client) {
DoStuff(); // receive and send data
Close();
}
}
void Close() {
_client.Close();
_client = null;
}
Given that that the code calls the Close() method, which closes the _client socket and sets it to null, while still inside the `using’ block, what exactly happens behind the scenes? Does the socket really get closed? Are there side effects?
P.S. This is using C# 3.0 on the .NET MicroFramework, but I suppose the c#, the language, should function identically. The reason i am asking is that occasionally, very rarely, I run out of sockets (which is a very precious resource on a .NET MF devices).
Dispose will still be called. All you are doing is pointing the variable _client to something else in memory (in this case: null). The object that _client intially referred to will still be disposed at the end of the using statement.
Run this example.
Setting the variable to null is not destroying the object or preventing it from being disposed by the using. All you are doing is changing the reference of the variable, not changing the object originally referenced.
Late edit:
Regarding a discussion from the comments about MSDN’s using reference http://msdn.microsoft.com/en-us/library/yh598w02.aspx and the code in the OP and in my example, I created a simpler version of the code like this.
(And, yes, the object still gets disposed.)
You could infer from the link above that the code is being rewritten like this:
Which would not dispose the object, and that does not match the behavior of the code snippet. So I took a look at it through ildasm, and the best I can gather is that the original reference is being copied into a new address in memory. The statement
foo = null;applies to the original variable, but the call to.Dispose()is happening on the copied address. So here is a look at how I believe the code is actually being rewritten.For reference, this is what the IL looks like through ildasm.
I don’t make a living staring at ildasm, so my analysis can be classified as caveat emptor. However, the behavior is what it is.