Search code examples
c#try-catchusing

using and try finally, what should I choose


I have the following code block;

using (var msResp = new MemoryStream(Resp))
{
    try
    {
        Response resp = new Response(msResp);
        SetClientIdentityResponseValue sirv = new SetClientIdentityResponseValue(resp, (int)Response.Properties.Value);
        if (!sirv.IsCredentialsValid)
        {
            throw new Exception("Authentication failed.");
        }
        if (sirv.IsSubscriptionExpired)
        {
            throw new Exception("Subscription expired.");
        }
    }
    finally
    {
        msResp.Close();
    }
}

I have read somewhere that a using statement automatically disposes the object.

Question:

Is using the Try/Finally combination redundant, when I already use the using statement?


Solution

  • Yes, it is redundant.

    The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

    using Statement (C# Reference)