Re: Problems Handling Errors Correctly
- From: "Carl Daniel [VC++ MVP]" <cpdaniel_remove_this_and_nospam@xxxxxxxxxxxxxxx>
- Date: Sat, 15 Sep 2007 15:03:02 -0700
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
.
- Follow-Ups:
- Re: Problems Handling Errors Correctly
- From: Jonathan Wood
- Re: Problems Handling Errors Correctly
- References:
- Problems Handling Errors Correctly
- From: Jonathan Wood
- Re: Problems Handling Errors Correctly
- From: Peter Duniho
- Re: Problems Handling Errors Correctly
- From: Jonathan Wood
- Problems Handling Errors Correctly
- Prev by Date: Re: string startswith or endswith a double quote?
- Next by Date: Re: dates
- Previous by thread: Re: Problems Handling Errors Correctly
- Next by thread: Re: Problems Handling Errors Correctly
- Index(es):
Relevant Pages
|