TextReader and StreamReader

T

Tony Johansson

Hello!

I just wonder in this specific case is it any advantage to use a
TextReader a reference to a StreamReader ?

Try
{
TextReader tr = new StreamReader(locationTextBox.Text);
Try
{
displayTextBox.Text = tr.ReadToEnd();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message)
}
finally
{
tr.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}

//Tony
 
R

raylopez99

Tony said:
Hello!

I just wonder in this specific case is it any advantage to use a
TextReader a reference to a StreamReader ?

Not that I can see--but I'm a novice.

My book says there are three front end Stream adapters in C#: (1)
StreamReader/Writer (for text), (2) BinaryReader/Writer (for int,
flota,string) and (3) XMLReader/Writer (for XML data).

Then you have decorator streams for the middle stuff (stuff like
CryptoStream to encrypt), and then at the back end you have backing
store streams (to save to file or memory or a network, namely,
respectively, FileStream, MemoryStream and NetworkStream, with
IsolatedStorageSystem also used for encrypted files).

That's it.

Why tempt fate by trying something different? You'll lose hours.
Stick to the tried and true is my suggestion.

RL
 
M

Marc Gravell

Not really; this type of abstraction is handy (for example) as
arguments to a method, but within a single method? Not really.

Actually, in this case, the simplest thing (in .NET 2.0 at least) is
probably File.ReadAllText:

displayTextBox.Text = File.ReadAllText(locationTextBox.Text);

Marc
 
J

Jon Skeet [C# MVP]

Tony Johansson said:
I just wonder in this specific case is it any advantage to use a
TextReader a reference to a StreamReader ?

In addition to Marc's answer - by declaring the variable as TextReader
instead of StreamReader, you're giving someone reading the code the
information that you don't need any of the extra functionality from
StreamReader - just the members on TextReader (with the implementation
appropriate to a StreamReader, of course).
 

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