release resources by using a using statement

T

Tony Johansson

Hello!

Below I have a simple using construction. When this go out of scope which
close will be called
is the one in TextReader or the one in StreamReader

It must be the one in TextReader otherwise it's very strange.
The reson I ask it that a book called step by step C# 2005 is saying that
close in StreamReader will be called which must be totally wrong.

using (TextReader reader = new StreamReader(fullPathname))
{
string line;
while ((line = reader.ReadLine()) != null)
{
source.Text += line + "\n";
}
}

//Tony
 
A

Arne Vajhøj

Tony said:
Below I have a simple using construction. When this go out of scope which
close will be called
is the one in TextReader or the one in StreamReader

It must be the one in TextReader otherwise it's very strange.
The reson I ask it that a book called step by step C# 2005 is saying that
close in StreamReader will be called which must be totally wrong.

using (TextReader reader = new StreamReader(fullPathname))
{
string line;
while ((line = reader.ReadLine()) != null)
{
source.Text += line + "\n";
}
}

It calls StreamReader Close, because what you have is an instance
of StreamReader. This is how polymorphism works.

Arne
 
J

Jon Skeet [C# MVP]

Tony Johansson said:
Below I have a simple using construction. When this go out of scope which
close will be called
is the one in TextReader or the one in StreamReader

It must be the one in TextReader otherwise it's very strange.
The reson I ask it that a book called step by step C# 2005 is saying that
close in StreamReader will be called which must be totally wrong.

using (TextReader reader = new StreamReader(fullPathname))
{
string line;
while ((line = reader.ReadLine()) != null)
{
source.Text += line + "\n";
}
}

It will actually call TextReader.Dispose() which will in turn call the
virtual Dispose(bool) method - which is overridden by StreamReader.

I don't see why you thought it "must be totally wrong" however - the
whole point of polymorphism is that if StreamReader *did* override
TextReader.Dispose() (which it can't in this particular case, as
TextReader.Dispose is non-virtual) then the StreamReader implementation
would be called.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top