Question

After a bit of advice here, regarding best practice coding - I am still a beginner with regards to C#. I have been reading on how using blocks are essential for disposing objects and attempting to implement these.

My question however, is if you are declaring and initialising a variable, should this be in a using block also?

I have tested and it seems to compile fine. But would appreciate peoples thoughts on this.

Thanks,

Was it helpful?

Solution

Using blocks are only helpful with objects that implement the IDisposable interface. It roughly translates to having a try...finally block that disposes the object in the finally. You can see more detail here.

OTHER TIPS

It is common practice to declare a variable closest to where you need it. If it not used outside of the using block (or any other block) there's usually no reason to declare it outside.

The answer to your question "Should this be in the using block also?" is truly a matter of scope. Variables declared in the scope of your block (try, using, etc) will fall out of scope when the block is exited.

Consider the following two examples:

  1. Declare variable, assign in block, exit block, require variable.

    WebHeaderCollection headers;
    
    using (var cl = new WebClient())
    {
        headers = cl.ResponseHeaders;
    }
    
    // headers is still in scope
    foreach (var k in headers.AllKeys) 
        Debug.WriteLine("{0} : {1}", k, headers[k]);
    
  2. Declare and assign variable in block, exit block, require variable

    using (var cl = new WebClient())
    {
        var headers = cl.ResponseHeaders;
    
        // use headers here, just fine
        foreach (var k in headers.AllKeys) 
            Debug.WriteLine("{0} : {1}", k, headers[k]);
    }
    
    // headers is no longer in scope
    foreach (var k in headers.AllKeys) 
        Debug.WriteLine("{0} : {1}", k, headers[k]);
    

Option #2 throws an exception. So, first determine the scope requirement of your variable and then decide if you need it after the using block ends.

No. Putting any variable inside a using is just not necessary. It's basically help for the RAII idiom, which in .NET is commonly useful only for objects that wrap / use an unmanaged resource. And the standard pattern for those objects is to implement a IDisposable. The using keyword is just some nice syntax sugar for

try{ 
  //initialize and use variable 
} 
finally { 
  //cast to IDisposable - if not null, call Dispose()
}

So even though it will compile and work, it's no use at all if your object doesn't implement IDisposable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top