473,738 Members | 4,774 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

more about the using statement

Hello!

I just wonder what is the point of having the reader variable declared as
TextReader in the snippet below..
Is it because of using the polymorfism on the reader variable perhaps.

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

//Tony

Jan 16 '08 #1
23 1724
On Wed, 16 Jan 2008 10:33:24 -0800, Tony Johansson
<jo************ *****@telia.com wrote:
Hello!

I just wonder what is the point of having the reader variable declared as
TextReader in the snippet below..
Is it because of using the polymorfism on the reader variable perhaps.
In the example you give, there's really not any difference. The reference
only ever is stored in one variable, and that variable could just as
easily have been a StreamReader.

But since StreamReader and StringReader simply implement the abstract
TextReader class without adding anything new, it's nice to use them as
TextReaders. The same thing would apply to any other class someone might
derive from TextReader. That way the code is more general-purpose and
doesn't depend on a specific implementation of TextReader. Of course,
usually this would be a matter of passing the local variable to some
method that takes a TextReader, and of course that can be done whether or
not the variable is declared explicitly as just a TextReader versus a
StreamReader.

Obviously at some point you need to be explicit about which class is
created, but this only needs to be done in one specific place and the rest
of the code can be more reusable by using TextReader instead.

To some extent, declaring the local variable as a TextReader just makes it
that much more clear that the code within the using statement isn't
dependent at all on the reader being a StreamReader. Here, it's likely an
issue of code readability as anything else.

Pete
Jan 16 '08 #2
A StreamReader is a "type" of TextReader and that's why the code works. If
you ask me for fruit and I pass you an apple, it is ok, because an apple is
a "type" of fruit. This isn't quite polymorphism at work here, but simple
inheritance concepts.

Having said that, since a StreamReader is a more specific "type" than a
TextReader, you probably wouldn't want to keep this line of code as it is.
You'd want to declare reader as a StreamReader so that you can take full
advantage of a StreamReader's members in the using block. As it is now,
you'd only be able to use the more generic members of a TextReader in the
using block even though you really do have a StreamReader in memory.

-Scott
"Tony Johansson" <jo************ *****@telia.com wrote in message
news:U5******** *********@newsb .telia.net...
Hello!

I just wonder what is the point of having the reader variable declared as
TextReader in the snippet below..
Is it because of using the polymorfism on the reader variable perhaps.

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

//Tony

Jan 16 '08 #3
Hi,

In that sentence using as another meaning, it basically do two things, first
it create a scope for the variable reader and second and more importantly it
call Dispose at the end of the scope.
In this construction you do not have to close the Reader. as the Dispose
method will do it for you, even if an exception is throw inside the scope.

Of course the variable being "used" must implement IDisposable

--
Ignacio Machin
http://www.laceupsolutions.com
Mobile & warehouse Solutions.
"Tony Johansson" <jo************ *****@telia.com wrote in message
news:U5******** *********@newsb .telia.net...
Hello!

I just wonder what is the point of having the reader variable declared as
TextReader in the snippet below..
Is it because of using the polymorfism on the reader variable perhaps.

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

//Tony

Jan 16 '08 #4
Scott M. <sm**@nospam.no spamwrote:
A StreamReader is a "type" of TextReader and that's why the code works. If
you ask me for fruit and I pass you an apple, it is ok, because an apple is
a "type" of fruit. This isn't quite polymorphism at work here, but simple
inheritance concepts.

Having said that, since a StreamReader is a more specific "type" than a
TextReader, you probably wouldn't want to keep this line of code as it is.
You'd want to declare reader as a StreamReader so that you can take full
advantage of a StreamReader's members in the using block. As it is now,
you'd only be able to use the more generic members of a TextReader in the
using block even though you really do have a StreamReader in memory.
I prefer to only declare variables as the minimally specific type that
I need them to be. That makes it obvious that if you need to change the
implementation that happens to be used at a later date, it's okay to do
so.

In other words, I think the code is absolutely fine as it is :)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Jan 16 '08 #5
Hi,


"Jon Skeet [C# MVP]" <sk***@pobox.co mwrote in message
news:MP******** *************@m snews.microsoft .com...
Scott M. <sm**@nospam.no spamwrote:
>Having said that, since a StreamReader is a more specific "type" than a
TextReader, you probably wouldn't want to keep this line of code as it
is.
You'd want to declare reader as a StreamReader so that you can take full
advantage of a StreamReader's members in the using block. As it is now,
you'd only be able to use the more generic members of a TextReader in the
using block even though you really do have a StreamReader in memory.

I prefer to only declare variables as the minimally specific type that
I need them to be. That makes it obvious that if you need to change the
implementation that happens to be used at a later date, it's okay to do
so.

In other words, I think the code is absolutely fine as it is :)

I totally agree with you, there is nothing wrong with that code . Not only
that but I wish that ALL the code were always written like that. I have
found a lot of places where objects that implement IDisposables are nt being
used like tht and are not being disposed after use.

--
Ignacio Machin
http://www.laceupsolutions.com
Mobile & warehouse Solutions.
Jan 16 '08 #6
On Jan 16, 7:43 pm, "Ignacio Machin \( .NET/ C# MVP \)" <machin TA
laceupsolutions .comwrote:
Hi,

"Jon Skeet [C# MVP]" <sk...@pobox.co mwrote in messagenews:MP* *************** *****@msnews.mi crosoft.com...
Scott M. <s...@nospam.no spamwrote:
Having said that, since a StreamReader is a more specific "type" than a
TextReader, you probably wouldn't want to keep this line of code as it
is.
You'd want to declare reader as a StreamReader so that you can take full
advantage of a StreamReader's members in the using block. As it is now,
you'd only be able to use the more generic members of a TextReader in the
using block even though you really do have a StreamReader in memory.
I prefer to only declare variables as the minimally specific type that
I need them to be. That makes it obvious that if you need to change the
implementation that happens to be used at a later date, it's okay to do
so.
In other words, I think the code is absolutely fine as it is :)

I totally agree with you, there is nothing wrong with that code . Not only
that but I wish that ALL the code were always written like that. I have
found a lot of places where objects that implement IDisposables are nt being
used like tht and are not being disposed after use.

--
Ignacio Machinhttp://www.laceupsolut ions.com
Mobile & warehouse Solutions.

Nothing wrong with the code...

good use of the using statement - I always try to use the using
statement on any object which implements IDispose - but surely the
StringBuilder object should be employed instead of the string
concatination within a loop!!
Jan 16 '08 #7
<ma************ *@ntlworld.comw rote:

<snip>
Nothing wrong with the code...

good use of the using statement - I always try to use the using
statement on any object which implements IDispose - but surely the
StringBuilder object should be employed instead of the string
concatination within a loop!!
Oh absolutely. My mistake for not being clearer - I was only commenting
on the declaration of the variable as a TextReader.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
Jan 16 '08 #8
Hello!

Because the TextReader is an abstract class it mean that some method in the
TextReader class does not have an implementation. A wonder which method in
the TextReader class does not have an implementation which mean that the
method implemention must be done in the derived class in this case the
StreamReader class.

//Tony
"Peter Duniho" <Np*********@nn owslpianmk.coms krev i meddelandet
news:op******** *******@petes-computer.local. ..
On Wed, 16 Jan 2008 10:33:24 -0800, Tony Johansson
<jo************ *****@telia.com wrote:
>Hello!

I just wonder what is the point of having the reader variable declared as
TextReader in the snippet below..
Is it because of using the polymorfism on the reader variable perhaps.

In the example you give, there's really not any difference. The reference
only ever is stored in one variable, and that variable could just as
easily have been a StreamReader.

But since StreamReader and StringReader simply implement the abstract
TextReader class without adding anything new, it's nice to use them as
TextReaders. The same thing would apply to any other class someone might
derive from TextReader. That way the code is more general-purpose and
doesn't depend on a specific implementation of TextReader. Of course,
usually this would be a matter of passing the local variable to some
method that takes a TextReader, and of course that can be done whether or
not the variable is declared explicitly as just a TextReader versus a
StreamReader.

Obviously at some point you need to be explicit about which class is
created, but this only needs to be done in one specific place and the rest
of the code can be more reusable by using TextReader instead.

To some extent, declaring the local variable as a TextReader just makes it
that much more clear that the code within the using statement isn't
dependent at all on the reader being a StreamReader. Here, it's likely an
issue of code readability as anything else.

Pete

Jan 16 '08 #9
On Wed, 16 Jan 2008 13:26:21 -0800, Tony Johansson
<jo************ *****@telia.com wrote:
Hello!

Because the TextReader is an abstract class it mean that some method in
the
TextReader class does not have an implementation. A wonder which method
in
the TextReader class does not have an implementation which mean that the
method implemention must be done in the derived class in this case the
StreamReader class.
Is that a question? If so, you may want to rephrase it. Possibly
including a question mark, to make it clear where the question is. I have
no idea what, if any, response might be expected with respect to the above.

Pete
Jan 16 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

22
2324
by: bearophile | last post by:
Ville Vainio: >It's highly typical for the newbies to suggest improvements to the >language. They will usually learn that they are wrong, but the >discussion that ensues can be fruitfull anyway :-). Few more notes on the language. I don't know if I can really suggest improvements to the language... but I hope to learn something :-) I think some things are better in Delphi/Pascal (like the := for assignments instead of = and = for...
1
2130
by: M Wells | last post by:
Hi All, Further to my previous long-winded question about a situation in which we appear to be mysteriously losing data from our mssql2k server. We discovered an update statement, in the stored procedure we believe is at fault, after which no error check was being performed. Under certain conditions, this update is fired against the same record in the same table as the immediately preceding update statement within
3
7505
by: Colin Spalding | last post by:
In Access, if I want to update one table with information from another, all I need to do is to create an Update query with the two tables, link the primary keys and reference the source table(s)/column(s) with the destination table(s)/column(s). How do I achieve the same thing in SQL? Regards Colin *** Sent via Developersdex http://www.developersdex.com ***
7
2147
by: Tony Johansson | last post by:
Hello Experts! I have the following Array template class see below. I execute these three statements statement 1: Array<int> x(5); statement 2: cin >>x; statement 3: Array<int>::element_type y = x; but I can't understand the last one which is Array<int>::element_type y = x; We have a typedef T element_type; in the template Array class see below
5
6591
by: Rod | last post by:
I have a client site where the code below has been working happily for at least four months. The site is using SQL Server 7. The code is ASP.NET Last week an error appeared related to the following SQL statement. INSERT INTO OrderItems (ClientID, ProductID, OrderHeaderID, Quantity, Dispatched, BackOrdered) SELECT ClientID, ProductID, 1371 AS OrderHeaderID, Quantity, Dispatched, BackOrdered FROM Basket WHERE RequisitionID = 1369 The...
4
3284
by: allenevaalleneva | last post by:
Q:Write a program that prints the numbers 1 to 4 on the same line with with each pair of adjacent numbers separated by one space. Do this several ways: a) Using one statement with one stream insertion operator. b) Using one statement with four stream insertion operators. c) Using for statement my answers are as follow a)
8
2807
by: rbg | last post by:
I did use query plans to find out more. ( Please see the thread BELOW) I have a question on this, if someone can help me with that it will be great. In my SQL query that selects data from table, I have a where clause which states : where PermitID like @WorkType order by WorkStart DESC
15
16070
by: Dave | last post by:
I am getting the error above intermittantly with an ASP 3.0 page using an MS Access 2003 database. I have searched Google extensively and found the following possible causes for this error: A field name was spelled incorrectly. One or more of the values was blank. You tried to insert the wrong datatype (e.g. surrounded a numeric value with quotes, or forgot to put quotes around a string).
1
1798
by: =?Utf-8?B?bGlhbnF0bGl0?= | last post by:
Is using a jump statement more faster than using if statement with a jump statement example for(int i=0; i < 10; i++) { if(a == null) {
0
8788
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9476
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9335
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
6751
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6053
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4570
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3279
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2745
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.