0

I use a dll and I haven't its source code. Somebody advised me to use a fonction of this dll like this :

void IDSCallback.Received(NetworkStream a)
{
    using (a)
    {
        // Some code...
    }
}

I don't understand the purpose of the using. At the end of this function, a.Dispose() is called so a is no longer usable.

So the function which called the IDSCallback.Received() can't use it anymore.

Why the using is in the function IDSCallback.Received() and not in the function which called IDSCallback.Received() ?

2
  • 7
    a should certainly not be disposed in this method as Received does not own it. Commented Jun 19, 2014 at 8:32
  • 2
    You should only use using on objects whose lifetime you actually want to limit. Somebody is wrong. Unless it is proper of you to close the stream as part of the Received message (e.g. as part of a "close" message or something), you shouldn't do that. For the most part, it's a bad idea to use using on things that aren't basically local variables you've just created :) Commented Jun 19, 2014 at 8:38

2 Answers 2

1

It's something similar to javas auto resource closing try-catch. Take a look at the documentation

In your context you should not dispose the parameters. You should rather do it where you create it:

void IDSCallback.Received(NetworkStream a)
{
    //..
}

and where you create it:

using (NetworkStream  a = /* Create the stream */)
{
    IDSCallback.Received(a);
    // Do whatever else you want with it
}
Sign up to request clarification or add additional context in comments.

Comments

1

A using is a try/finally block to make sure that the Dispose() method is called on the resource. See MSDN documentation for how it is interpreted by the compiler.

The question of whether you need to use a using statement or not in the IDSCallback.Received method depends on the contract the method has with the calling code, and, unless there is a compelling reason, it should not be disposing a resource it did not construct. As a result, there should be no using statement either.

The advice could have been for the code that calls IDSCallback.Received method to use the using statement so once the NetworkStream is no longer needed, it can be disposed off properly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.