开发者

C# Using Clause - Clarification

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();
    ...
}


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜