Re: Problems Handling Errors Correctly

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



Jonathan Wood wrote:
Peter,

Actually, it is simple.

Well now, I do recall how hard the .NET developers tried to find a
solution to the lack of deterministic finalization, so I don't quite
agree that "it is simple" tells the entire story.

You need webResponse to be in a using block, yes. But note that
since the "using() { }" block itself qualifies as a statement, you
can simply put two using statements with each other:

using (HttpWebResponse webResponse =
(HttpWebResponse)webRequest.GetResponse())
using (StreamReader reader = new
StreamReader(webResponse.GetResponseStream()))
{
// code here
}

If you prefer, you could do this instead, which is equivalent to the
above:

using (HttpWebResponse webResponse =
(HttpWebResponse)webRequest.GetResponse(),
StreamReader reader = new
StreamReader(webResponse.GetResponseStream()))
{
// code here
}

I do prefer, but this gives me the error: Cannot use more than one
type in a for, using, fixed, or declaration statement.

The first version does compile.

It need not be messy.

For that matter, how about webRequest?

No.

Because it doesn't implement IDisposable?

Correct.


Yes. If the class implements IDisposable, then you need the "using"
statement. If it doesn't, you don't.

And what's the quickest way to find out? If it has a Dispose() method?

....or RTFM.


Also, can you tell me if the using statement eliminates the need to
call the Close() method on these objects?

Yes, it does.

-cd


.



Relevant Pages

  • Re: Problems Handling Errors Correctly
    ... Well now, I do recall how hard the .NET developers tried to find a solution to the lack of deterministic finalization, so I don't quite agree that "it is simple" tells the entire story. ... using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse) ... using (StreamReader reader = new StreamReader(webResponse.GetResponseStream())) ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Problems Handling Errors Correctly
    ... But I find that in practice (in large part due to the lack of deterministic finalization), ... object clean up in a timely manner no matter what, ... using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse) ... using (StreamReader reader = new StreamReader(webResponse.GetResponseStream())) ...
    (microsoft.public.dotnet.languages.csharp)