Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The scope of C#'s using keyword

I understand that any time I am instantiating a class that implements IDisposable, I should use the using keyword in order to ensure that it's disposed of properly.

Like so:

using (SecureString s = new SecureString())
{

}

The above is easy for me to understand - I can use s however I want within those brackets, but once I leave those brackets, I can no longer refer to s. The scope is easy to see.

But what I don't understand is how it works when you use using with no enclosing brackets.

private void Function()
{
    // Some code here

    using (SecureString s = new SecureString())

    // more code here
}

You aren't required to use brackets at all... so... how do I know where I am able to use the object and where it gets disposed, if there are no brackets to go with the using keyword?

like image 393
Ryan Ries Avatar asked Oct 17 '13 14:10

Ryan Ries


1 Answers

In almost every case in C# when you have the choice of using braces you can substitute them with a single line of code.

Consider an if statement:

if (someBool)
    DoSomething();
else
    DoSomethingElse();

That is just as valid as the following:

if (someBool)
{
    // do lots of things
}
else
    DoSomethingElse();

This is probably almost universally true for any time you can use the { and } brackets.

The nice thing about this with the using statement is that you can nest them like this:

using (var stream = new NetworkStream(...))
using (var sslStream = new SslStream(stream))
using (var reader = new StreamReader(sslStream))
{
    reader.WriteLine(...);
}

This is equivalent to the following:

using (var stream = new NetworkStream(...))
{
    using (var sslStream = new SslStream(stream))
    {
        using (var reader = new StreamReader(sslStream))
        {
            reader.WriteLine(...);
        }
    }
}

Although I think you'd agree it's much nicer looking.

like image 74
Trevor Elliott Avatar answered Sep 30 '22 21:09

Trevor Elliott