Max
Max

Reputation: 13338

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?

Upvotes: 0

Views: 110

Answers (4)

D Stanley
D Stanley

Reputation: 152556

Since you're calling Close rather than Dispose It's not blatantly obvious that the code is redundant.

The documentation for MemoryStream.Dispose indicates that the stream is closed when calling Dispose:

This method disposes the stream, by writing any changes to the backing store and closing the stream to release resources.

Which infers that Close is called. However, there's no harm in explicitly Closing the stream when you're done with it.

Bottom line: Is it redundant? Probably. Is it hurting anthing? Absolutely not. I'd prefer to be in the habit of cleaning up after myself, even if a janitor comes in behind me and has nothing to do (or cleans again).

Upvotes: 0

Azhar Khorasany
Azhar Khorasany

Reputation: 2709

Its redundant. But remember, if you want to catch exception then you need a try-catch. using statement won't catch any exceptions. It just close and disposes the object.

Upvotes: 1

Ryan M
Ryan M

Reputation: 2112

You don't need the finally. In fact, the using block is implemented internally using a try... finally.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

Upvotes: 1

jrummell
jrummell

Reputation: 43077

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)

Upvotes: 4

Related Questions