Apaachee
Apaachee

Reputation: 900

Using a variable in a function

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() ?

Upvotes: 0

Views: 68

Answers (2)

Balázs Édes
Balázs Édes

Reputation: 13807

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
}

Upvotes: 1

Omer Iqbal
Omer Iqbal

Reputation: 2293

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.

Upvotes: 1

Related Questions