C# - Is there a reason NOT to instantiate a class and use it in a single line of code?

Viewed 102

I know this would be a correct way to use a StreamWriter:

using (StreamWriter sw = new StreamWriter(hreq.GetRequestStream()))
    sw.Write(jsonPostData);

But what about this? Is this also valid or to be avoided? Would it be properly disposed?

new StreamWriter(hreq.GetRequestStream()).Write(jsonPostData);
2 Answers

When using IDisposables (i.e., usually external resources), you need to call Dispose() on them. using is syntactic sugar that does that for you, but the principal remains - you use some special call to make sure Dispose() is called. In the second snippet, Dispose() is not called, and you'll leak a resource until the program terminates.

Just wanted to share a safer version:

// In case hreq.GetRequestStream() returns a readonly stream,
// which causes new StreamWriter(Stream) to throw exception
using (var stream = hreq.GetRequestStream())
{
    using (var sw = new StreamWriter(stream))
    { 
        sw.Write(jsonPostData);
    }
}
Related