Search code examples
c#variablesusing

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


Solution

  • 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
    }