2

I understand what the using clause does, but should it be used with unnamed parameters?

For example; should:

var navigator = new XPathDocument(new StringReader(request)).CreateNavigator(); 

be:

using (StringReader sr = new StringReader(request)) { var navigator = new XPathDocument(sr).CreateNavigator(); ... } 
4
  • yes, I would use the second code block. Commented Aug 26, 2011 at 7:48
  • Does it make a difference whether it's named or unnamed? Commented Aug 26, 2011 at 7:48
  • @BoltClock - that is the question ... Commented Aug 26, 2011 at 7:49
  • I was referring to if you declared StringReader sr without the using block. Commented Aug 26, 2011 at 7:50

4 Answers 4

2

It makes no difference whether you are assigning the object implementing IDisposable to a variable, you should still be disposing it and hence you should use Using.

Sign up to request clarification or add additional context in comments.

Comments

1

Best way to know how it works : test!

class Program { public static void Main() { using (TestDisposable d = new TestDisposable()) { } // Will trace "disposed" UseDisposable use = UseDisposable.Create(new TestDisposable()); // Will trace "disposed" } } public class UseDisposable { public TestDisposable Disposable; public static UseDisposable Create(TestDisposable disposable) { return new UseDisposable() { Disposable = disposable }; } } public class TestDisposable : IDisposable { private bool _disposed = false; #region IDisposable Membres public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Dispose(bool disposing) { if(!_disposed && disposing) { Trace.WriteLine("Disposed"); _disposed = true; } } #endregion } 

In my opinion, you should always use the second method.

Comments

1

Your first code piece is equivalent to this:

StringReader sr = new StringReader(request); var navigator = new XPathDocument(sr).CreateNavigator(); 

The difference is that you dont create an explicit "handle" for your StringReader and therefore lose the ability to work with it later on (e.g.: disposing it).

Therefore you should be using the "using" clause. It also enhances the readability.

Comments

0

Yes you should use this if you can. I think the MS code analysis even warns you if you don't.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.